_getch()函數的作用是獲取按鍵信息,且該函數在conio.h中定義。_getche()函數與_getch()函數函數類似,
其作用也是獲取按鍵信息,並且也是在conio.h中定義。_getch()函數不會在控制檯中顯示按鍵信息。_getch()函數是一個阻塞函數,直到有字符輸入時纔會返回,所以該函數不會返回錯誤值。
#define _CRT_SECURE_NO_WARNINGS
#include "iostream"
#include "conio.h"
#include "string"
using namespace std;
int main()
{
char a;
int i = 0;
string PassWord;
cout << "請輸入密碼:";
while(1)
{
a = _getch(); //獲取輸入的密碼
if (a == 13) //回車返回
{
break;
}
if (a == 8) //退格
{
if (PassWord.length() == 0) //如果第一個鍵爲退格鍵
{
cout << "密碼爲空,請輸入密碼:";
continue;
}
cout << "\b \b";
i++; //清除所要刪掉的字符
PassWord[PassWord.length() - i] = '\0';
}
else
{
PassWord += a;
cout << "*";
}
}
cout << endl;
cout <<"密碼爲:" <<PassWord << endl;
cout << endl;
system("pause");
return 0;
}