Hiding User Input from Standard Input
When retrieving sensitive information like passwords from standard input, displaying the typed characters is undesirable. This article explores platform-agnostic methods to disable character echoing during input.
Code Example
Consider the following code snippet:
string passwd; cout << "Enter the password: "; getline(cin, passwd);
This code prompts the user to enter a password, but the characters typed are visibly displayed. To conceal user input, we employ platform-specific techniques outlined below.
Platform-Specific Solutions
Windows
#ifdef WIN32 #include <windows.h>
In Windows systems, SetConsoleMode can be used to toggle character echoing. Disable echoing by setting ENABLE_ECHO_INPUT to 0:
SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), mode & ~ENABLE_ECHO_INPUT);
Linux/macOS
#else #include <termios.h>
For Linux and macOS systems, tcgetattr and tcsetattr are employed to retrieve and update terminal settings. Disable echoing by clearing the ECHO bit in the c_lflag field:
tty.c_lflag &^= ECHO; tcsetattr(STDIN_FILENO, TCSANOW, &tty);
Final Code
Combining these techniques, the following code provides a cross-platform solution to disable character echoing during password input:
#include <iostream> #include <string> 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 } int main() { SetStdinEcho(false); std::string password; std::cin >> password; SetStdinEcho(true); std::cout << password << std::endl; return 0; }
The above is the detailed content of How Can I Hide User Input from the Console During Password Entry?. For more information, please follow other related articles on the PHP Chinese website!