std :: stringstream一次只支持一个输入?

时间:2014-02-03 12:33:42

标签: c++ std

由于std::stringstream是一个stzream,并且根据此处的documention,您可以执行流支持的任何操作。

所以我希望以下示例能够正常工作,但似乎并非如此。我正在使用MingW和gcc 4.8.3。

变式A:

std::string s;
std::stringstream doc;
doc << "Test " << "String ";
doc << "AnotherString";
doc >> s;
std::cout << s << std::endl;

变体B:

std::string s;
std::stringstream doc;
doc << "Test ";
doc << "AnotherString";
doc >> s;
std::cout << s << std::endl;

此输出仅为

Test 

虽然我期望它会连接各个字符串,直到我从流中读回我放在那里的内容。

那么连接字符串的方法是什么?我是否真的需要单独读出每一个并手动连接它们,这对我来说在C ++中看起来很尴尬。

2 个答案:

答案 0 :(得分:2)

它将每个字符串放入doc,以便其内容为:

Test String AnotherString

然后,当您使用doc >> s进行提取时,它只读取第一个空格。如果要将整个流作为字符串获取,可以调用str

std::cout << doc.str() << std::endl;

答案 1 :(得分:1)

使用stream >> s只能读取一个字直到空格。除了@ JosephMansfield使用str()的答案之外,您还可以使用getline()(如果您的字符串不包含新行,则效果很好):

getline(doc, s);
相关问题