Home >Backend Development >C++ >How Can I Read Passwords from Standard Input Without Echoing Them?
Reading Passwords from std::cin without Echoing
The need to read passwords from standard input without echoing the input characters arises regularly. To achieve this, it's essential to disable the echo on std::cin.
Windows and UNIX Differences
The method for disabling echo depends on the operating system. In Windows, the GetConsoleMode and SetConsoleMode functions are used, while in UNIX-like systems, tcgetattr and tcsetattr are employed.
Implementing the Solution
The provided code snippet includes an OS-agnostic function, SetStdinEcho, which allows toggling echo for std::cin. A sample usage is also provided, demonstrating how to read a password without echoing and then echo it when the user presses enter:
#include <iostream> #include <string> int main() { SetStdinEcho(false); std::string password; std::cin >> password; SetStdinEcho(true); std::cout << password << std::endl; return 0; }
This code ensures the user's password remains private while being entered and displayed upon successful input.
The above is the detailed content of How Can I Read Passwords from Standard Input Without Echoing Them?. For more information, please follow other related articles on the PHP Chinese website!