How do I hide user input with cin in C++? [duplicate]

笑着哭i 提交于 2019-12-01 14:00:09

问题


Possible Duplicate:
Read a password from std::cin

I'm trying to make a simple password program so I can get familiar with C++, but I'm having a bit of a problem. In this code, I ask the user for a password they choose, and then they enter it. What I want to code to do is hide the input (not replace it with *s), but still show the cursor, and the text above, before, and after the password is entered, like this:

Please enter password: [don't show input]
Please re-enter password: [don't show input]

How can I do this? I'm using Linux, so I won't be able to use any windows libraries (windows.h, etc).


回答1:


You cannot do this directly using cin. You have to go "lower". Try calling these functions:

#include <termios.h>

...

void HideStdinKeystrokes()
{
    termios tty;

    tcgetattr(STDIN_FILENO, &tty);

    /* we want to disable echo */
    tty.c_lflag &= ~ECHO;

    tcsetattr(STDIN_FILENO, TCSANOW, &tty);
}

void ShowStdinKeystrokes()
{
   termios tty;

    tcgetattr(STDIN_FILENO, &tty);

    /* we want to reenable echo */
    tty.c_lflag |= ECHO;

    tcsetattr(STDIN_FILENO, TCSANOW, &tty);
}



回答2:


You'll want to call tcsetattr and modify the ECHO flag.



来源:https://stackoverflow.com/questions/13694170/how-do-i-hide-user-input-with-cin-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!