Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unechoed string input in C++

Tags:

c++

I am writing a program in C++ where I am supposed to receive a string from user without displaying it on screen (for example: apassword). I tried using cin and gets to accept the string. But both will echo the characters entered by user in console.

So is there any function or any other way of doing it in C++?

like image 562
ZoomIn Avatar asked Feb 15 '12 11:02

ZoomIn


1 Answers

How to avoid that data being read via cin shows up on the console depends very much on the console; it's certainly operating system dependant.

On Windows, you can use the SetConsoleMode function to enable/disable the echo for any file handle, including the standard input handle.

Something like

void enableStdinEcho( bool b ) {
    HANDLE hStdin = ::GetStdHandle( STD_INPUT_HANDLE ); 
    DWORD mode = 0;
    ::GetConsoleMode( hStdin, &mode );
    if ( b ) {
        mode |= ENABLE_ECHO_INPUT;
    } else {
        mode &= ~ENABLE_ECHO_INPUT;
    }
    ::SetConsoleMode( hStdin, mode );
}

could probably be used to toggle the echo on stdin.

like image 134
Frerich Raabe Avatar answered Oct 12 '22 16:10

Frerich Raabe