我发现很难全神贯注于 stringstream
的工作。为什么下面代码中的第二个 while 循环不起作用?如果流对象在第一个 while 循环结束时被清空,是否有任何解决方法可以将其恢复到初始状态?
// input is string of numbers separated by spaces (eg. "22 1 2 4")
std::string input;
std::getline(std::cin, input);
stringstream stream (input);
// print individual numbers
while (stream >> n)
{
cout << n << endl;
}
// print individual numbers again
while (stream >> n)
{
cout << n << endl;
}
最佳答案
stringstream
是 istream
的子类, 所以 stream >> n
( std::istream::operator>>
) 返回 reference to istream
stream
可以转换为bool
( std::ios::operator bool
):它转换为 false
当它不再有任何数据时(到达文件末尾)
您已阅读完stream
在你的第一个循环中 - 它不再有任何数据。
If stream object is getting emptied at the end of the first while loop is there any workaround to restore it back to initial condition?
您需要自己存储值然后重用它们 - 不允许复制流(这对它们真的没有意义)- Why copying stringstream is not allowed?
关于c++ - 多次使用 stringstream 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53336255/