我正在尝试读取密码,当我读取它时,显示 **。
cout << "\n Insert password : ";
loop1:
string passw1 = "";
char ch = _getch();
while (ch != 13) // enter = char 13
{
if (!isalnum(ch))
{
cout << "\n\n Invalid character! Please insert the password again! ";
goto loop1;
}
passw1.push_back(ch);
cout << "*";
ch = _getch();
}
如果我按例如 、 BACKSPACE 或 SPACE 或其他非字母数字的东西,一切都会按计划进行。问题是当我按任何 F 键,或 DELETE、HOME、INSERT、END、PG UP、PG DOWN 时程序崩溃。你能帮我避免坠机吗?我想在按下无效键时显示一条错误消息,而不是让我的程序崩溃。
最佳答案
让我们看看我是否理解您想要做什么(用伪代码):
Prompt the user for a password
Wait for the user to press any key
While the key pressed is not the enter key
If the entered key is an alphanumeric
Add the character to the password string
Print an asterisk on the screen
Accept another character
Else
Alert the user that they entered a non-alphanumeric
Clear out the string and have the user start over again
End If
End While
如果这不是您想要的,请根据口味进行修改。
我认为正在发生的事情是,当您测试按下的键时,您没有捕获所有可能的字符。如果 DEL
给您带来了麻烦,那么找出如何捕捉或处理它(从屏幕上删除一个星号,并从字符串中删除一个字符)。
祝你好运!
关于C++密码字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8682131/