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++?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With