Vargas Vargas - 20 days ago 4x
C++ Question

Reading a password from std::cin

I need to read a password from standard input and wanted

not to echo the characters typed by the user...

How can I disable the echo from std::cin?

here is the code that I'm currently using:

string passwd;
cout << "Enter the password: ";
getline( cin, passwd );

I'm looking for a OS agnostic way to do this.
Here there are ways to do this in both Windows and *nix.


@wrang-wrang answer was really good, but did not fulfill my needs, this is what my final code (which was based on this) look like:

void SetStdinEcho(bool enable = true)
#ifdef WIN32
    HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); 
    DWORD mode;
    GetConsoleMode(hStdin, &mode);

    if( !enable )
        mode &= ~ENABLE_ECHO_INPUT;
        mode |= ENABLE_ECHO_INPUT;

    SetConsoleMode(hStdin, mode );

    struct termios tty;
    tcgetattr(STDIN_FILENO, &tty);
    if( !enable )
        tty.c_lflag &= ~ECHO;
        tty.c_lflag |= ECHO;

    (void) tcsetattr(STDIN_FILENO, TCSANOW, &tty);