问题
I need to create a simple password program where the program asks user to input password and when user inputs, it shows the characters as asterisks.
Every tutorial out there uses getch()
(in conio.h
). But I don't want to use it. Is there any easy alternative for doing so?
I'm using Windows 10.
P.S: Please don't confuse this to be a duplicate of this question: Alternative function in iostream.h for getch() of conio.h?
Because that question asks for holding screen output whereas I need to mask the input as asterisks.
回答1:
We are here in non standard functionality. So, whatever you'll do, it will not be portable.
The native console way would be to ReadConsoleInput() as explained here. In your case, you would first disable the echo and the line input mode by clearing the console mode flags ENABLE_LINE_INPUT
and ENABLE_ECHO_INPUT
. Then you would react on key events by displaying '*'. Don't forget to restore the inital console mode at the end.
A shortcut would be to just save and change the console mode (as shown in the code above), an then looping for cin.get()
and echoing cout<<'*';
followed by cout.flush();
to be sure that the output doesn't wait in a buffer, creating discomfort for the user.
来源:https://stackoverflow.com/questions/58571242/masking-the-user-input-as-asterisks-in-windows