Masking the user input as asterisks in Windows?

落花浮王杯 提交于 2021-02-05 06:43:24

问题


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

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