Var*_*gas 53 c++ stl password-protection
我需要从标准输入读取密码,并且不想std::cin回显用户输入的字符...
如何禁用std :: cin的回声?
这是我目前使用的代码:
string passwd;
cout << "Enter the password: ";
getline( cin, passwd );
我正在寻找一种与操作系统无关的方法来做到这一点. 这里有一些方法可以在Windows和*nix中执行此操作.
Var*_*gas 64
@ 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;
}
如果您不关心可移植性,可以使用_getch()in VC.
#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()的wide characters.我的建议是你也使用系统中NCurse可用的*nix.