C语言基本输入
在C语言中,有多个函数可以从键盘获得用户输入:
-
scanf():和printf()类似,scanf()可以输入多种类型的数据;
-
getchar():输入单个字符;
-
gets():获取一行数据,作为字符串进行处理;
-
getche():window平台特有输入函数,无缓冲的获取单个输入字符;
-
getch():window平台特有输入函数,无缓冲无回显的获取单个输入字符。
其中,scanf()是格式化输入函数,可通过格式控制符控制获取输入数据的类型。
部分scanf()格式控制符如下:
scanf()函数的高级用法
scanf()控制字符串的完整写法为:%{*} {width} type
其中带有{}符号的表示控制字符串可以有这一项,也可以没有这一项
*:*号表示丢弃读取到的数据
width:width表示最大读取宽度
type:type表示读取的数据类型
通过getch()函数可实现模拟密码输入,代码如下:
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#define PWD_LENGTH 20
void get_pwd(char* pwd, int pwd_length);
int main()
{
char pwd[PWD_LENGTH + 1] = {0};
printf("Input password: ");
get_pwd(pwd, PWD_LENGTH);
printf("The password is %s.\n", pwd);
system("pause");
return 0;
}
void get_pwd(char* pwd, int pwd_length)
{
char ch;
int i = 0;
while(i < pwd_length)
{
ch = getch();
if(ch == '\r')
{
printf("\n");
break;
}
else if((ch == '\b') && (i > 0))
{
i--;
printf("\b \b");
}
else if(isprint(ch))
{
pwd[i] = ch;
printf("*");
i++;
}
}
pwd[i] = '\0';
}