Search code examples
c++buffercinflush

Strange behavior of cin


I've been practicing a bit of C ++. It is a simple program, however i've playing with the terminal and I noticed a strange behavior when entering the password in 'input'. It appears that the buffer 'triggers' before the 'Give me the password' message. How could I avoid this strange behavior?.

I'm using Eclipse IDE for C/C++ Developers

Version: Neon.3 Release (4.6.3) Build id: 20170314-1500

Thanks in advance

#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 BehaviorThis the Correct Behavior

Incorrect BehaviorThis the Incorrect Behavior


Solution

  • That's really weird. There doesn't seem to be a reason besides the compiler producing bad code for your OS or something. I recommend getting Visual Studio 2017 if that's possible.

    Try a wait after you write to cout.