之前有遇到需求說輸入密碼不顯示明文,但同時會有一些其他問題,暫時沒做,如今經過嘗試可以實現,但是得先知道要輸入的是密碼。主要利用的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 }
功能是輸入字符不顯示或者顯示其他字符,按下回車或結束輸入,並且將剛才輸入的密碼顯示出來。不同效果如下: