C++输入密码不显示明文

之前有遇到需求说输入密码不显示明文,但同时会有一些其他问题,暂时没做,如今经过尝试可以实现,但是得先知道要输入的是密码。主要利用的getch()函数的不回显特点。需要注意的是这个函数不是标准函数,而且使用VS2013有提示换成_getch()。具体代码以及效果如下:

 1 /*
 2 2018年9月13日21:24:48
 3 
 4 实现输入密码时候不显示明文
 5 
 6 */
 7 
 8 
 9 #include <iostream>
10 
11 #include <string>
12 #include <conio.h>
13 using namespace std;
14 
15 //https://zhidao.baidu.com/question/235215029.html
16 string getpasswordwithoutplaindata()
17 {
18     string ret;
19     char ch;
20     ch = _getch();
21     while (ch != '\n' && ch != '\r')
22     {
23         ret += ch;
24         //cout << "debug:" << ret << endl;
25         ch = _getch();
26     }
27 
28     return ret;
29 
30 }
31 
32 string getpasswordwithstar()
33 {
34     string ret;
35     char ch;
36     ch = _getch();
37     while (ch != '\n' && ch != '\r')
38     {
39         _putch('*');
40         ret += ch;
41         ch = _getch();
42     }
43 
44     return ret;
45 
46 }
47 
48 
49 string getpasswordanotherchar(char rch)
50 {
51     string ret;
52     char ch;
53     ch = _getch();
54     while (ch != '\n' && ch != '\r')
55     {
56         _putch(rch);
57         ret += ch;
58         ch = _getch();
59     }
60 
61     return ret;
62 
63 }
64 
65 int main()
66 {
67     string password;
68     cout << "input your password:" << endl;
69     //password = getpasswordwithoutplaindata();
70     //password = getpasswordwithstar();
71     password = getpasswordanotherchar('+');
72     cout <<"\nThe password you input is :"<< password << endl;
73     return 0;
74 }


功能是输入字符不显示或者显示其他字符,按下回车或结束输入,并且将刚才输入的密码显示出来。不同效果如下:

猜你喜欢

转载自www.cnblogs.com/youdias/p/9643456.html