从std :: cin读取密码 [英] Reading a password from std::cin

查看:212
本文介绍了从std :: cin读取密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to read a password from standard input and wanted std::cin not to echo the characters typed by the user...

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

How can I disable the echo from std::cin?

这里是我目前使用的代码:

here is the code that I'm currently using:

string passwd;
cout << "Enter the password: ";
getline( cin, passwd );

我正在寻找一个操作系统不可知的方式来做到这一点。
这里有办法在Windows和* nix。

I'm looking for a OS agnostic way to do this. Here there are ways to do this in both Windows and *nix.

推荐答案

@ wrang-wrang答案真的很好,但没有满足我的需要,这是我的最终代码基于)看起来像:

@wrang-wrang answer was really good, but did not fulfill my needs, this is what my final code (which was based on this) look like:

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
}

这篇关于从std :: cin读取密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆