在cpp奇怪的范围

Liu*_*Liu 3 c++ scoping

当我使用字符串流时,我的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)

为什么会这样?

Mat*_*son 7

当你stringstream为每一行"创建并销毁"时,它也会fail重置状态.

您可以通过line.clear();在添加新内容之前添加来解决此问题line.