Hide user input on password prompt

dom0 picture dom0 · Aug 1, 2011 · Viewed 38.2k times · Source

Possible Duplicate:
Read a password from std::cin

I don't work normally with the console, so my question is maybe very easy to answer or impossible to do .

Is it possible to "decouple" cin and cout, so that what I type into the console doesn't appear directly in it again?

I need this for letting the user typing a password and neither me nor the user normally wants his password appearing in plaintext on the screen.

I tried using std::cin.tie on a stringstream, but everything I type is still mirrored in the console.

Answer

user195488 picture user195488 · Aug 1, 2011

From How to Hide Text:

Windows

#include <iostream>
#include <string>
#include <windows.h>

using namespace std;

int main()
{
    HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); 
    DWORD mode = 0;
    GetConsoleMode(hStdin, &mode);
    SetConsoleMode(hStdin, mode & (~ENABLE_ECHO_INPUT));

    string s;
    getline(cin, s);

    cout << s << endl;
    return 0;
}//main 

cleanup:

SetConsoleMode(hStdin, mode);

tcsetattr(STDIN_FILENO, TCSANOW, &oldt);

Linux

#include <iostream>
#include <string>
#include <termios.h>
#include <unistd.h>

using namespace std;

int main()
{
    termios oldt;
    tcgetattr(STDIN_FILENO, &oldt);
    termios newt = oldt;
    newt.c_lflag &= ~ECHO;
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);

    string s;
    getline(cin, s);

    cout << s << endl;
    return 0;
}//main