在Windows中将用户输入屏蔽为星号? [英] Masking the user input as asterisks in Windows?

查看:70
本文介绍了在Windows中将用户输入屏蔽为星号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个简单的密码程序,该程序要求用户输入密码,并在用户输入时将其显示为星号.

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.

每个教程都使用 getch()(在 conio.h 中).但我不想使用它.有没有简便的替代方法?

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?

我正在使用Windows 10.

I'm using Windows 10.

PS:请不要将其与以下问题重复:

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.

推荐答案

我们在此处提供非标准功能.因此,无论您做什么,它都不是可移植的.

We are here in non standard functionality. So, whatever you'll do, it will not be portable.

本机控制台方式是 ReadConsoleInput() ,如此处所述>.对于您的情况,您首先要通过清除控制台模式标志 ENABLE_LINE_INPUT ENABLE_ECHO_INPUT 来禁用回波和线路输入模式.然后,您将通过显示"*"来对关键事件做出反应.最后不要忘记恢复初始控制台模式.

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.

一种快捷方式是保存并更改控制台模式(如上面的代码所示),然后循环 cin.get()并回显 cout<<'*'; 后跟 cout.flush(); ,以确保输出不会在缓冲区中等待,从而使用户感到不适.

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.

这篇关于在Windows中将用户输入屏蔽为星号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆