Yve*_*ves 5 c++ string stringstream
我正在尝试在 的帮助下逐字循环字符串stringstream,这是我的代码:
string str = "hello world";
stringstream ss(str);
string word;
while (ss)
{
ss >> word;
cout << word << endl;
}
Run Code Online (Sandbox Code Playgroud)
但是,我得到的结果如下:
hello
world
world
Run Code Online (Sandbox Code Playgroud)
为什么我得到了world两次?
while (ss)看到ss还没有遇到问题,所以它运行循环体。ss(这就是当你用作布尔值时会发生的情况)ss >> word;读作“你好”cout << word << endl;打印“你好”while (ss)看到ss还没有遇到问题,所以它再次运行循环体。ss >> word;读作“世界”cout << word << endl;打印“世界”while (ss)看到ss还没有遇到问题,所以它再次运行循环体。ss >> word;看到没有更多数据,所以失败。word没有改变,仍然包含“world”cout << word << endl;打印“世界”while (ss)看到ss遇到了问题并停止循环。需要检查读完单词后是否停止循环。例如,与:
while (true)
{
ss >> word;
if (!ss)
break;
cout << word << endl;
}
Run Code Online (Sandbox Code Playgroud)
或简称:
while (ss >> word)
{
cout << word << endl;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
668 次 |
| 最近记录: |