c++ - 从 std::cin 读取密码

标签 c++ stl password-protection

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

如何禁用来自 std::cin 的回显?

这是我目前使用的代码:

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

我正在寻找一种与操作系统无关的方法来执行此操作。 Here在 Windows 和 *nix 中都有办法做到这一点。

最佳答案

@wrang-wrang 的回答非常好,但没有满足我的需求,这就是我的最终代码(基于 this )的样子:

#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;
}

关于c++ - 从 std::cin 读取密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23665376/

相关文章:

c++ - 具有来自 STL 的 vector 、列表或映射作为成员的类是否需要复制构造函数

c++ - 从 std::cin 读取密码

php - Bcrypt(4)(=4 次迭代)与 SHA512 或每个密码具有唯一盐分的不同内容?

vba - 为什么此代码会禁用工作表保护?

c++ - Eigen 矩阵 vector 除法

c++ - 使用迭代器范围将单个元素附加到容器

c++ - 适用于 Windows 7 的 OpenGL

c++ - v <int> pos(MAX)v <int> tmp是非类类型 ‘__gnu_cxx::__alloc_traits<std::allocator<int>>::value_type {aka int}’ pos [i] .push_back(tmp);

c++ - 使用 std::map 评估表达式树

c++ - OpenGL 中的拱门(2D 或 3D)