_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;
}