当我使用字符串流时,我的cpp程序在使用作用域时做了一些奇怪的事情.当我将字符串和字符串流的初始化放在与我使用它的块相同的块中时,没有问题.但是如果我将它放在上面的一个块中,则字符串流不能正确输出字符串
正确的行为,程序打印由空格分隔的每个标记:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main () {
while (true){
//SAME BLOCK
stringstream line;
string commentOrLine;
string almostToken;
getline(cin,commentOrLine);
if (!cin.good()) {
break;
}
line << commentOrLine;
do{
line >> almostToken;
cout << almostToken << " ";
} while (line);
cout << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
行为不正确,程序只打印第一个输入行:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main () {
//DIFFERENT BLOCK
stringstream line;
string commentOrLine;
string almostToken;
while (true){
getline(cin,commentOrLine);
if (!cin.good()) {
break;
}
line << commentOrLine;
do{
line >> almostToken;
cout << almostToken << " ";
} while (line);
cout << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
| 归档时间: |
|
| 查看次数: |
79 次 |
| 最近记录: |