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

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

问题描述

可能重复:
从std::cin读取密码

我不能正常使用控制台,所以我的问题可能很容易回答或不可能做到.

I don't work normally with the console, so my question is maybe very easy to answer or impossible to do .

是否可以将cincout解耦",这样我在控制台中输入的内容就不会再次直接出现在其中了?

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

我需要这个来让用户输入密码,而我和用户通常都不希望他的密码以 plaintext 出现在屏幕上.

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天全站免登陆