在密码提示时隐藏用户输入 [英] Hide user input on password prompt

查看:153
本文介绍了在密码提示时隐藏用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

从std :: cin 读取密码

是否可以解耦可以使用控制台正常工作,因此我的问题可能很容易回答或不可能做。 cin cout ,这样我在控制台中输入的内容不会再直接显示在其中了吗?

Is it possible to "decouple" cin and cout, so that what I type into the console doesn't appear directly in it again?

我需要这样做让用户输入密码,我和用户都不希望他的密码出现在屏幕上的明文中。

I need this for letting the user typing a password and neither me nor the user normally wants his password appearing in plaintext on the screen.

我试着在 stringstream 上使用 std :: cin.tie 但是我键入的内容仍然在控制台中镜像。

I tried using std::cin.tie on a stringstream, but everything I type is still mirrored in the console.

推荐答案

如何隐藏文字

Windows

#include <iostream>
#include <string>
#include <windows.h>

using namespace std;

int main()
{
    HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); 
    DWORD mode = 0;
    GetConsoleMode(hStdin, &mode);
    SetConsoleMode(hStdin, mode & (~ENABLE_ECHO_INPUT));

    string s;
    getline(cin, s);

    cout << s << endl;
    return 0;
}//main 

清除:

SetConsoleMode(hStdin, mode);

tcsetattr(STDIN_FILENO, TCSANOW, &oldt);

Linux

#include <iostream>
#include <string>
#include <termios.h>
#include <unistd.h>

using namespace std;

int main()
{
    termios oldt;
    tcgetattr(STDIN_FILENO, &oldt);
    termios newt = oldt;
    newt.c_lflag &= ~ECHO;
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);

    string s;
    getline(cin, s);

    cout << s << endl;
    return 0;
}//main 

这篇关于在密码提示时隐藏用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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