我正试图在stringstream
的帮助下逐字循环一个字符串,这是我的代码:
string str = "hello world";
stringstream ss(str);
string word;
while (ss)
{
ss >> word;
cout << word << endl;
}
然而,我得到的结果如下:
hello
world
world
为什么我得了两次world
?
使用以下代码片段:
while (ss) { ... }
您正在检查string stream
的状态。如果它包含有效数据,循环将继续。这就是为什么你看到最后一个词两次。。。
1st循环迭代:
while ( ss ) { // checks if there is valid data in ss and for errors (true) ss >> word; // ss inserts "hello" into word. cout << word << endl; // cout prints "hello" to the console. }
2nd循环迭代:
while ( ss ) { // checks again if there is valid data (true) ss >> word; // ss inserts "world" into word. cout << word << endl; // cout prints "world" to the console. }
3rd循环迭代:
while ( ss ) { // checks again if there is valid data (true) ss >> word; // ss already contains "world", may optimize or copy over... cout << word << endl; // cout prints "world" to the console. }
4th循环迭代:
while ( ss ) { // ss encountered end of stream (false) exits loop. ss >> word; // nothing inserted as loop has exited. cout << word << endl; // nothing printed as loop has exited. }
不要尝试将stringstream
用作循环的条件,而是尝试使用从stringstream
中提取数据到条件变量中的过程。
while( ss >> word ) {
cout << word << endl;
}
1st循环迭代:
while ( ss >> word ) { // checks if ss inserted data into word // ss inserts "hello" (true) cout << word << endl; // cout prints "hello" to the console. }
2nd循环迭代:
while ( ss >> word ) { // checks again if ss inserted data into word // ss inserts "world" into word (true) cout << word << endl; // cout prints "world" to the console. }
3rd循环迭代:
while ( ss >> word ) { // checks again if ss inserted data into word // ss fails to insert data (false) loop exits here cout << word << endl; // nothing printed as loop exited }
while (ss)
发现ss
还没有遇到问题,所以它运行循环体。(将ss
用作布尔值时会发生这种情况(ss >> word;
读"你好">cout << word << endl;
打印"你好">while (ss)
看到ss
还没有遇到问题,所以它再次运行循环体ss >> word;
读"世界">cout << word << endl;
打印"世界">while (ss)
看到ss
还没有遇到问题,所以它再次运行循环体ss >> word;
看到没有更多的数据,所以它失败了。word
不变,它仍然包含着"世界">cout << word << endl;
打印"世界">- CCD_ 20发现CCD_ 21遇到问题并停止循环
您需要检查是否在读取单词后停止循环。例如,使用:
while (true)
{
ss >> word;
if (!ss)
break;
cout << word << endl;
}
或简称:
while (ss >> word)
{
cout << word << endl;
}