从std :: cin读取密码

Var*_*gas 53 c++ stl password-protection

我需要从标准输入读取密码,并且不想std::cin回显用户输入的字符...

如何禁用std :: cin的回声?

这是我目前使用的代码:

string passwd;
cout << "Enter the password: ";
getline( cin, passwd );
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种与操作系统无关的方法来做到这一点. 这里有一些方法可以在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
}
Run Code Online (Sandbox Code Playgroud)

样品用法:

#include <iostream>
#include <string>

int main()
{
    SetStdinEcho(false);

    std::string password;
    std::cin >> password;

    SetStdinEcho(true);

    std::cout << password << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*ehl 11

标准中没有任何内容可供选择.

在unix中,您可以根据终端类型编写一些魔术字节.

如果可用,请使用 getpasswd.

system()/usr/bin/stty -echo可以禁用echo,并/usr/bin/stty echo启用它(再次,在unix上).

这家伙解释了怎么做而不使用"stty"; 我自己没试过.


Ara*_*raK 7

如果您不关心可移植性,可以使用_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 << '*';
    }
}
Run Code Online (Sandbox Code Playgroud)

还有getwch()wide characters.我的建议是你也使用系统中NCurse可用的*nix.