Hide user input on password prompt [duplicate]

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 

Leave a Comment