我需要从标准输入中读取密码并希望 std::cin
不回显用户输入的字符...
如何禁用来自 std::cin 的回显?
这是我目前使用的代码:
string passwd;
cout << "Enter the password: ";
getline( cin, passwd );
我正在寻找一种与操作系统无关的方法来执行此操作。 Here在 Windows 和 *nix 中都有办法做到这一点。
最佳答案
@wrang-wrang 的回答非常好,但没有满足我的需求,这就是我的最终代码(基于 this )的样子:
#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
}
示例用法:
#include <iostream>
#include <string>
int main()
{
SetStdinEcho(false);
std::string password;
std::cin >> password;
SetStdinEcho(true);
std::cout << password << std::endl;
return 0;
}
关于c++ - 从 std::cin 读取密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23665376/