Hide user input when prompted for password

Possible duplicate:
Read the password from std :: cin

I do not work well with the console, so my question is probably very easy to answer or make impossible.

Is it possible to "untie" cin and cout , so that what I type into the console does not appear directly in it again?

I need this so that the user enters a password, and neither I nor the user usually want their password to be displayed in plaintext on the screen.

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

+12
source share
3 answers

From How to hide text :

Window

 #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 

Cleaning:

 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 
+29
source

You are really asking about two unrelated issues.
Calling cin.tie( NULL ) drops std::cin and std::cout completely. But it does not affect anything at a lower level. And at the lowest level, at least under Windows and Unix, std::cin and std::cout both connected to the same device at the system level, and it is this device ( /dev/tty under Unix) that performs the echo signal; you can even redirect the standard version to a file, and the console will still have an echo input.

How you disable this echo is system dependent; the simplest solution is probably to use some kind of third-party library, such as curses or ncurses, which provides a higher-level interface and hides all system dependencies.

+5
source

Use getch() to get the input instead of using cin , so the input will not be displayed (wiki quoting):

int getch (void) Reads a character directly from the console without a buffer and without an echo.

This is really C, not C ++, but it might suit you.

Also here is another link .

+2
source

All Articles