Skip to content

Instantly share code, notes, and snippets.

@theriverman
Created February 11, 2019 23:04
Show Gist options
  • Save theriverman/ee1a625bcb7b4ee363bb04329a1195e3 to your computer and use it in GitHub Desktop.
Save theriverman/ee1a625bcb7b4ee363bb04329a1195e3 to your computer and use it in GitHub Desktop.

Revisions

  1. theriverman created this gist Feb 11, 2019.
    40 changes: 40 additions & 0 deletions getUserPassword.hpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    /*
    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
    }