如何用相同的stringstream对象标记两个不同的字符串?

时间:2013-03-13 03:27:29

标签: c++ tokenize

如何使用相同的stringstream对象标记两个不同的字符串?

我正在尝试以下代码,但它不起作用:

using namespace std;

void check()
{
        stringstream s( "This is a test");
        string token;

        while (s>>token)
        {
              cout<< token <<'\n';
        }
        s.str("hello world");
        while ( s>> token )
        {
              cout<< token <<'\n';
        }
}

int main()
{
    check();
    int z;
    cin>>z;
}

2 个答案:

答案 0 :(得分:3)

您需要通过s.clear();

重置流标记
stringstream my_stringstream( "This is a test");
string token;

while ( my_stringstream >> token )
{
      cout<< token <<'\n';
}

my_stringstream.str("hello world");
my_stringstream.clear();

while ( my_stringstream >> token )
{
      cout<< token <<'\n';
}

当您在第一个while循环中使用>>到达流的末尾时,将设置eof位。这就是为什么你需要调用clear()来重置流,如答案所示 谢谢Jesse Good的补充。

答案 1 :(得分:0)

这一行:

while (s >> token)

......确实很多。除了从token获取s之外,operator>>还会返回流(s)。然后whileconverting it to either a bool (since C++11) or a void* (before C++11)评估此s。这基本上! fail()相同。现在,如果fail()返回true并且您已经退出第一个循环,那么在eofbitbadbit和/或{{{{}}之前,您不会进入第二个循环1}}已被重置。您可以使用clear()重置这些内容,如下所示:

failbit

See it run

相关问题