我们在实现密码输入时需要保证输入的内容不能被别人看到,同时要具备可以一次性输入的特点,因而getch()函数便具备了这些优点。
1.getch()函数包含在头文件<conio.h>中
特点:无回显、接受键盘一次输入
getch()函数不属于标准输入输出函数(stdio.h),每次用户从键盘输入的数据并不会经过键盘缓冲区存储,而是直接可以被终端所接受。
2.具体代码实现:
#include <stdio.h>
#include <conio.h>
int main(void)
{
char password[20],ch;
int i=0;
while(1)
{
ch=getch();
if(ch=='\r')//当读到回车符时输入结束
{
break;
}
password[i++]=ch;
printf("*");
}
password[i]='\0';//需要在字符的末尾补加字符串结束标志,才可以以字符串形式输出
printf("%s",password);
return 0;
}
3.程序运行图