多次使用 stringstream 对象

Using stringstream object multiple times

我发现很难全神贯注于 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>>)returns一个reference to istream

stream can be converted to 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?

您需要先创建 stringstream,以便多次传递您已读入 input 的内容。 input 本身只是一个 string 而不是 stream#include <sstream> 然后在阅读 input 后创建 stringstream

std::stringstream stream (input);

然后您可以使用第一个 while 循环读取,但第二个 while 将不起作用,因为流位置在第一个 while 之后留在 stringsteam 的末尾eofbit 已设置。

您需要调用 stream.seekg(0) 到 "rewind" 文件并清除 eofbit,请参阅:在第二个 while 循环之前 std::basic_istream::seekg

它没有被清空,但是一旦你到达终点,你就会卡在终点——就像其他溪流一样。

您需要清除错误标志 (stream.clear()),然后倒带 (stream.seekg(0)) 或重置输入字符串 (stream.str(input))。