问题
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