c++ - 多次使用 stringstream 对象

标签 c++ stringstream

我发现很难全神贯注于 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;
    }

最佳答案

stringstreamistream 的子类, 所以 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/

相关文章:

javascript - 如何将 JavaScript 中的字符串与 Geany 中的制表符和回车符连接起来?

c++ - 使用 C++ 读取带有两个连续分隔符的 csv 文件

c++ - 不匹配 'operator='(操作数类型为 'book' 和 '<brace-enclosed initializer list>')

C++读取文件直到空间

c++ - 一旦执行完成就杀死子进程(在fork之后)

c++ - 递归函数偶尔会返回段错误

C++ stringstreams with std::hex

c++ - 将 int 放入 stringstream 时,它会插入奇怪的字符

c++ - 获取存储为字符串的数字的小数部分

stringstream - C++ 从 unsigned char* 到 stringstream : Segmentation fault (core dumped) error