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

2020-03-31 07:54发布

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).

2条回答
霸刀☆藐视天下
2楼-- · 2020-03-31 08:10

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);
}
查看更多
太酷不给撩
3楼-- · 2020-03-31 08:13

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

查看更多
登录 后发表回答