[英]Reading a password from std::cin
我需要从标准输入中读取密码,并希望std::cin
不回显用户输入的字符...
如何禁用 std::cin 的回声?
这是我目前使用的代码:
string passwd;
cout << "Enter the password: ";
getline( cin, passwd );
我正在寻找一种与操作系统无关的方式来做到这一点。 这里有一些方法可以在 Windows 和 *nix 中执行此操作。
@wrang-wrang 答案非常好,但没有满足我的需求,这就是我的最终代码(基于此)的样子:
#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;
}
如果你不关心可移植性,你可以在VC
使用_getch()
。
#include <iostream>
#include <string>
#include <conio.h>
int main()
{
std::string password;
char ch;
const char ENTER = 13;
std::cout << "enter the password: ";
while((ch = _getch()) != ENTER)
{
password += ch;
std::cout << '*';
}
}
wide characters
也有getwch()
。 我的建议是你使用NCurse
,它也在*nix
系统中可用。
只知道我有什么,您可以逐个字符读取密码字符,然后只打印退格键(“\\b”)和“*”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.