gpt4 book ai didi

c++ - 当 >> 字符串流时更改双引号的行为

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:02:58 26 4
gpt4 key购买 nike

这是我正在尝试做的事情:

假设我有一个字符串流。然后我<< "\"hello world\" today";

然后当我做

sstr >> myString1 >> myString2;

我希望 myString1 有“hello world”并且 myString2 有“今天”

有没有办法(可能是通过操纵器)实现这一点?

谢谢

最佳答案

简短回答:否

长答案:
没有任何操作可以为您做到这一点。

替代答案:

您可以编写自己的类型,与流运算符结合使用来完成此任务。

#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>


class QuotedWord
{
public:
operator std::string const& () const { return data;}

private:
std::string data;
friend std::ostream& operator<<(std::ostream& str, QuotedWord const& value);
{
return str << value.data;
}
friend std::istream& operator>>(std::istream& str, QuotedWord& value);
{
char x;
str >> x;
if ((str) && (x == '"'))
{
std::string extra;
std::getline(str, extra, '"');
value.data = std::string("\"").append(extra).append("\"");
}
else
{
str.putback(x);
str >> value.data;
}
return str;
}
};

然后就可以正常使用了。

int main()
{
QuotedWord word;

std::cin >> word;
std::cout << word << "\n";

// Easily convertible to string
std::string tmp = word;
std::cout << tmp << "\n"

// because it converts to a string easily it can be used where string is needed.
std::vector<std::string> data;

std::copy(std::istream_iterator<QuotedWord>(std::cin),
std::istream_iterator<QuotedWord>(),

// Notice we are using a vector of string here.
std::back_inserter(data)
);
}

> ./a.out
"This is" a test // Input
"This is" // Output
"This is"

关于c++ - 当 >> 字符串流时更改双引号的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4701535/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com