Skip to content

Instantly share code, notes, and snippets.

@Polda18
Last active February 23, 2019 11:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Polda18/6f3a90030ff57640f01341278273e150 to your computer and use it in GitHub Desktop.
Save Polda18/6f3a90030ff57640f01341278273e150 to your computer and use it in GitHub Desktop.
Hiding a user input
// source: https://stackoverflow.com/questions/6899025/hide-user-input-on-password-prompt
#include <iostream>
#include <string>
#ifdef WIN32 // Windows
#include <windows.h>
#else // Unix = Linux / Mac OS
#include <termios.h>
#include <unistd.h>
#endif
using namespace std; // Do not use this! Rather use direct reference as std::reference!
void hide_input(void);
void show_input(void);
int main(void)
{
string uname, passw;
cout << "Login > ";
getline(cin, uname);
hide_input();
cout << "Password > "
getline(cin, passw);
show_input();
cout << "Your login is '" << uname << "'." << endl;
cout << "Your password is '" << passw << "'." << endl;
return 0;
}
#ifdef WIN32
void hide_input(void)
{
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode = 0;
GetConsoleMode(hStdin, &mode);
SetConsoleMode(hStdin, mode & (~ENABLE_ECHO_INPUT));
}
void show_input(void)
{
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode = 0;
GetConsoleMode(hStdin, &mode);
SetConsoleMode(hStdin, mode | (ENABLE_ECHO_INPUT));
}
#else
void hide_input(void)
{
termios terminal_mode;
tcgetattr(STDIN_FILENO, &terminal_mode);
terminal_mode.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &terminal_mode);
}
void show_input(void)
{
termios terminal_mode;
tcgetattr(STDIN_FILENO, &terminal_mode);
terminal_mode.c_lflag |= ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &terminal_mode);
}
#endif
@Polda18
Copy link
Author

Polda18 commented Feb 7, 2018

OS Branching would not be used in real project directly in source code, just in Makefile to include appropriate libraries for Windows and Linux.

In real project, this method would be separated between login.h with raw definitions and login.win32.cpp and login.linux-i386.cpp with OS dependent implementations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment