std::getline(), while循环内容不是运行

std::getline(), while loop content not running

目标


c++ 的新手,在其他任何地方都没有找到关于这个问题的明确答案。我正在开发一个简单的程序,该程序从控制台中读取用户输入的消息。这是一个使用字符串 variables/concatenation.

的练习

我需要创建读取用户输入的循环,其中可能包含来自命令 shell 的多行输入。

所以我的函数需要读取该输入,同时忽略换行符,并在用户在新行上输入两个“&&”时结束。

尝试


所以这是我的功能:

string get_message() {
    string message, line;
    cout << "Enter the message > ";
    cin.ignore(256, '\n');
    while (getline(cin, line) && line != "&&") {
        message = message + " " + line;
        cout << message;
        cin.clear();
    }
    return message;
}

我 运行 遇到的问题是,在 while 循环中,直到找到 &&,运行 才显示循环内容。意思是当我 cout << message 我只得到前一行的输入。

样本运行


Enter the Message >  Messages.. this is a new message.
I'm a message on a new line, look at me.
New line.
&&
"New line." <--- from console cout

Result: New line.

问题:


分解:

string get_message() {
    string message, line;
    cout << "Enter the message > ";

标准的东西。这没东西看。继续前进。

    cin.ignore(256, '\n');

丢弃第一行或 256 个字符,以先到者为准。可能不是你想做的。从意识形态上讲,如果您认为流中已经存在垃圾,请在调用函数之前清空流。无论如何,绝对是 OP 问题的一部分。

    while (getline(cin, line) && line != "&&") {

虽然成功得到一行,但一行不是“&&”。看起来不错。注意:新行被 getline 函数剥离,因为它们是标记定界符,将它们留在返回的标记中或将它们留在流中只会导致问题。

        message = message + " " + line;

在消息中附加行

        cout << message;

写消息输出。没有进行刷新,因此无法预测消息何时到达屏幕。这可能是OP部分问题的原因。

        cin.clear();

清除 cin 上的错误条件。没有必要。如果 cin 处于错误状态,while 循环就不会进入。

    }
    return message;
}

正常的东西。这里没什么可看的,但是如果程序在这一点之后不久结束,调用 cout.flush(),将 std::flush 发送到 cout,或者有一个 cout << endl;,cout 将被刷新并且消息会突然出现

因此,使用 OP 的输入:

Messages.. this is a new message.

这被cin.ignore

抹杀了
I'm a message on a new line, look at me.

最终应该会出现。不知道为什么 OP 看不到它。我无法重现。

New line.

最终应该会出现。

&&

结束输入。

输出应该是:

I'm a message on a new line, look at me. I'm a message on a new line, look at me. New line.

而且我很困惑为什么 OP 在第一次刷新 cout 时没有得到这个。正如我所说,无法重现。

Return 应该是:

 I'm a message on a new line, look at me. New line.