我需要从标准输入中读取密码,并希望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/46794177/