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

其他提示

标准中没有任何内容。

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

如果可用,请使用 getpasswd

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

这个人解释了怎么做不使用“stty”;我自己没试过。

如果您不关心可移植性,可以在 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”)和“*”。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top