我正试图在stringstream
的帮助下逐字循环字符串,这是我的代码:
string str = "hello world";
stringstream ss(str);
string word;
while (ss)
{
ss >> word;
cout << word << endl;
}
但是,我得到的结果如下:
hello
world
world
为什么我两次获得world
?
答案 0 :(得分:2)
具有以下代码段:
while (ss) { ... }
您正在检查string stream
的状态。如果包含有效数据,则循环将继续。这就是为什么您两次看到最后一个单词...
1 st 循环迭代:
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. }
2 nd 循环迭代:
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. }
3 rd 循环迭代:
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. }
第4 th 循环迭代:
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;
}
1 st 循环迭代:
while ( ss >> word ) { // checks if ss inserted data into word // ss inserts "hello" (true) cout << word << endl; // cout prints "hello" to the console. }
2 nd 循环迭代:
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. }
3 rd 循环迭代:
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 }
答案 1 :(得分:1)
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;
打印“世界” while (ss)
发现ss
遇到问题并停止了循环。您需要检查 读取单词后是否停止循环。例如,使用:
while (true)
{
ss >> word;
if (!ss)
break;
cout << word << endl;
}
或简称:
while (ss >> word)
{
cout << word << endl;
}