cin

时间:2017-07-07 01:58:52

标签: c++ buffer cin flush

我一直在练习一些C ++。这是一个简单的程序,但是我在玩终端时,我注意到在输入'中输入密码时出现了一种奇怪的行为。似乎缓冲区触发了'在给我密码之前'信息。我怎么能避免这种奇怪的行为?。

我正在使用Eclipse IDE for C / C ++ Developers

版本:Neon.3发布(4.6.3) 构建ID:20170314-1500

提前致谢

#include <iostream>

using namespace std;

/*  DO WHILE EXAMPLE*/
int main() {

    const string password = "car";
    string input;
    do {
        cout << "Give me the password\n";
        cin >> input;

    if (input != password) {
            cout << "Incorrect Password\n";
    }

    } while (input != password);
    cout << "Correct Password";
    return 0;
}

Correct Behavior这是正确的行为

Incorrect Behavior这是不正确的行为

1 个答案:

答案 0 :(得分:0)

这真的很奇怪。除了编译器为您的操作系统或其他东西生成错误代码之外,似乎没有其他原因。如果可能的话,我建议使用Visual Studio 2017。

写完cout后尝试等待。