从std :: cin读取密码
-
06-07-2019 - |
题
我需要从标准输入读取密码,并希望 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 << '*';
}
}
宽字符
还有 getwch()
。我的建议是你使用 NCurse
。代码> * nix 系统也。
只知道我拥有的东西,你可以用char读取密码char,之后只打印退格(“\ b”)和“*”。
不隶属于 StackOverflow