C语言常用的输入函数有scanf、getchar和gets等。
1.使用scanf输入
scanf() 是通用的输入函数,它可以读取多种类型的数据。接收时的控制符号见下表:
| 控制符 | 说明 |
|---|---|
| %d | 接收整数 |
| %f | 接收小数 |
| %c | 接收字符 |
| 空格%c | 接收字符时忽略缓冲区上一次的残留字符 |
| %s | 接收字符串 |
注意:scanf() 是带有缓冲区的,scanf() 匹配到想要的数据后,会将匹配到的数据从缓冲区中删除,而没有匹配到的数据仍然会留在缓冲区中。
实例:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
int num;
float price;
char c;
char str[10];
scanf("%d",&num);
scanf("%f",&price);//注意:'\n'会滞留在缓冲区
scanf(" %c",&c);
scanf("%s",&str);
printf("\n-----------output result--------------\n");
printf("%d\n",num);
printf("%f\n",price);
printf("%c\n",c);
printf("%s\n",str);
return 0;
}
运行结果:
100
3.1415
A
hello,world!
-----------output result--------------
100
3.141500
A
hello,world!
如果使用字符串指针接收scanf输入,程序改写如下:
int main(){
int num;
float price;
char c;
//如果使用字符串指针必须先分配内存空间。
//char *str; //错误
char *str =(char *)malloc(sizeof(10));
scanf("%d",&num);
scanf("%f",&price);//注意:'\n'会滞留在缓冲区
scanf(" %c",&c);
scanf("%s",str); //str已经是指针无需使用取址符号。
printf("\n-----------output result--------------\n");
printf("%d\n",num);
printf("%f\n",price);
printf("%c\n",c);
printf("%s\n",str);
return 0;
}
2.getchar()接收单个字符 getchar();从键盘读取一个字符并输出,该函数的返回值是输入第一个字符的ASCII码;若用户输入的是一连串字符,函数直到用户输入回车时结束,输入的字符连同回车一起存入键盘缓冲区。若程序中有后继的getchar();函数,则直接从缓冲区逐个读取已输入的字符并输出,直到缓冲区为空时才重新读取用户的键盘输入。
另外一个函数getch()平时很少使用,但是大家可以简单了解它们的区别。
实例:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
float price;
char c1;
char c2;
scanf("%f",&price);
scanf(" %c",&c1);
scanf("%f",&price);
getchar(); //接收缓冲区里的'\n'
c2=getchar();
printf("\n--------output result-----------\n");
printf("%f\n",price);
printf("%c\n",c1);
printf("%c\n",c2);
return 0;
}
3.gets()专用的字符串输入函数
gets() 是专用的字符串输入函数,与 scanf() 相比,gets() 的主要优势是可以读取含有空格的字符串。 注意:gets() 也是有缓冲区的,我们可以使用getchar()先接收上次输入后留着缓冲区的回车。
实例:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
char str1[10];
char str2[10];
scanf("%s",str1);
getchar();
gets(str2);
printf("\n-------output result-----------\n");
printf("%s\n",str1);
printf("%s\n",str2);
return 0;
}
hello world
-------output result-----------
hello
world
当输入'hello world'时,由于scanf() 读取字符串时以空格为分隔,遇到空格就认为当前字符串结束了,所有把空格后的world赋给了str2。
hello,world
hello world
-------output result-----------
hello,world
hello world
分别输入'hello,world'和'hello world',可以验证gets() 能读取含有空格的字符串,而 scanf() 不能。
C语言的输出函数printf在前面章节已经做过详细讲解这里不再赘述。