Last active
February 23, 2019 11:23
-
-
Save Polda18/6f3a90030ff57640f01341278273e150 to your computer and use it in GitHub Desktop.
Hiding a user input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 andlogin.win32.cpp
andlogin.linux-i386.cpp
with OS dependent implementations.