Skip to content

Instantly share code, notes, and snippets.

@theriverman
Created February 11, 2019 23:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theriverman/ee1a625bcb7b4ee363bb04329a1195e3 to your computer and use it in GitHub Desktop.
Save theriverman/ee1a625bcb7b4ee363bb04329a1195e3 to your computer and use it in GitHub Desktop.
C++ password prompt with stdin masking
/*
Example code: https://gist.github.com/theriverman/b41daa62f5013126b77790b8165fcf74
ORIGINAL LOCATION OF CODE SNIPPET:
https://stackoverflow.com/questions/1413445/reading-a-password-from-stdcin
Credits: https://stackoverflow.com/users/121961/vargas
*/
#ifdef WIN32
#include <windows.h>
#else
#include <termios.h>
#include <unistd.h>
#endif
void SetStdinEcho(bool enable = true)
{
#ifdef WIN32
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode;
GetConsoleMode(hStdin, &mode);
if( !enable )
mode &= ~ENABLE_ECHO_INPUT;
else
mode |= ENABLE_ECHO_INPUT;
SetConsoleMode(hStdin, mode );
#else
struct termios tty;
tcgetattr(STDIN_FILENO, &tty);
if( !enable )
tty.c_lflag &= ~ECHO;
else
tty.c_lflag |= ECHO;
(void) tcsetattr(STDIN_FILENO, TCSANOW, &tty);
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment