多次提取和插入时出现奇怪的字符串流行为.

Kar*_*fel 1 c++ stringstream

有人可以帮我理解这个串流行为吗?

stringstream temp;
temp << "342 1 ";
int a;
while (temp >> a) {
    cout << a << endl;
}
temp << "56" << " ";
temp >> a;
cout << a << endl;
Run Code Online (Sandbox Code Playgroud)

哪个输出:

342
1
1
Run Code Online (Sandbox Code Playgroud)

我希望它输出

342
1
56
Run Code Online (Sandbox Code Playgroud)

这是在视觉工作室2015年编制的.

Bo *_*son 5

读取值1后,下一个while将到达文件结尾并将流置于错误状态.然后任何进一步的读取将失败,并a保持不变.

您可以通过调用清除错误状态 temp.clear().