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

Weird stringstream behavior when extracting and inserting multiple times.

谁能帮我理解这个 stringstream 行为?

stringstream temp;
temp << "342 1 ";
int a;
while (temp >> a) {
    cout << a << endl;
}
temp << "56" << " ";
temp >> a;
cout << a << endl;

输出:

342
1
1

我希望它输出

342
1
56

这是在 visual studios 2015 中编译的。

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

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