VS2017 C/C++输入密码显示*星号

VS2017  C/C++输入密码显示*星号

_getch()函数使用时遇到的坑

参考: https://blog.csdn.net/guin_guo/article/details/46237905
 
想实现输入密码不回显的功能,找到了上面一篇文章。上面那篇文章中的代码在dev里跑没有出现任何问题。
当我拿到VS2017里的时候,首先遇到的是getch()不安全,无奈去查相关内容,改成安全的做法_getch(),又出现了....蜜汁问题
问题1:输入一个字符回显两个星号
问题2:debug发现只能读进一个字符后便跳出循环
 
此处略去一天的瞎改瞎试瞎搜...
 
虽然我实现出我想要的功能效果了,还是不太明白为什么要用两个while
 
 1 //以下代码可在VS2017跑通,亲测
 2 #include<iostream>
 3 #include<conio.h> //使用里面的_getch()
 4 #include<cstring>
 5 #include<cstdlib>
 6 using namespace std;
 7 
 8 int main()
 9 {
10     char Real_password[50] = "password";
11     char s[50];//要输入的密码
12     char ch;
13     int i = 0;
14 
15     bool flg = false;
16 
17     while (true)
18     {
19         while (ch = _getch())
20         {
21             if (ch == '
')
22             {
23                 flg = true;
24                 break;
25             }
26             
27             if (ch != 8)//回撤是,ASCII码是8
28             {//不是回撤就录入 
29                 s[i] = ch;
30                 putchar('*');//输出星号 
31                 i++;
32             }
33             else
34             {
35                 putchar('');//回撤一个字符
36                 putchar(' ');//显示空格掩盖
37                 putchar('');//再回撤一格等待录入 
38                 i--;
39             }
40         }
41 
42         if (flg)
43             break;
44 
45     }
46     cout << endl;
47     s[i] = '';
48     cout << "密码:" << s << endl;
49 
50     if (strcmp(s, Real_password) == 0)
51         cout << "correct!" << endl;
52     else
53         cout << "wrong!" << endl;
54     system("pause");
55     return 0;
56 }

PS:

关于getch(),getche(),getchar()函数,网上的解释已经非常清楚了就不再赘述。

原文地址:https://www.cnblogs.com/christy99cc/p/10139910.html