
VS2017 C/C++输入密码显示*星号
_getch()函数使用时遇到的坑
参考: https://blog.csdn.net/guin_guo/article/details/46237905
想实现输入密码不回显的功能,找到了上面一篇文章。上面那篇文章中的代码在dev里跑没有出现任何问题。
当我拿到VS2017里的时候,首先遇到的是getch()不安全,无奈去查相关内容,改成安全的做法_getch(),又出现了....蜜汁问题
问题1:输入一个字符回显两个星号
问题2:debug发现只能读进一个字符后便跳出循环
此处略去一天的瞎改瞎试瞎搜...
虽然我实现出我想要的功能效果了,还是不太明白为什么要用两个while
//以下代码可在VS2017跑通,亲测 #include<iostream> #include<conio.h> //使用里面的_getch() #include<cstring> #include<cstdlib> using namespace std; int main() { ] = "password"; ];//要输入的密码 char ch; ; bool flg = false; while (true) { while (ch = _getch()) { if (ch == '\r') { flg = true; break; } )//回撤是\b,ASCII码是8 {//不是回撤就录入 s[i] = ch; putchar('*');//输出星号 i++; } else { putchar('\b');//回撤一个字符 putchar(' ');//显示空格掩盖 putchar('\b');//再回撤一格等待录入 i--; } } if (flg) break; } cout << endl; s[i] = '\0'; cout << "密码:" << s << endl; ) cout << "correct!" << endl; else cout << "wrong!" << endl; system("pause"); ; }
PS:
关于getch(),getche(),getchar()函数,网上的解释已经非常清楚了就不再赘述。