求高手解析scanf函数从标准读入char型和int型的区别
首先请看个小的测试程序
#include<stdio.h>
int main(void)
{
int a,b,c;
char m,n,i;
printf("pls input the value of a:");
scanf("%d",&a);
printf("pls input the value of b:");
scanf("%d",&b);
printf("pls input the value of c:");
scanf("%d",&c);
printf("pls input the chara m:");
scanf("%c",&m);
printf("pls input the chara n:");
scanf("%c",&n);
printf("pls input the chara i:");
scanf("%c",&i);
……
……
return 0;
}
我遇到的问题是:当我这样用几个scanf()一个一个读取数据时,int型数据 a,b,c成功一个一个输入读取成功。
但是,当我在准备输入char型数据,也就是准备输入字符时,他就一次性弹出了两个printf的内容
具体执行如下:
pls input the value of a:4
pls input the value of b:5
pls input the value of c:6
pls input the chara m:pls input the chara n:7(他一次性打印出来两行)
pls input the chara i:$(这里不等我输入就结束运行了)
如果我只是单独读取一个字符,用一个scanf可以读取, 但是连续用三个以上printf +scanf 就出现了刚刚出现的问题了。但是如果是读取整形数据就不会出现问题。请问这是为什么呢??
本人是初学者,请高手勿喷。
[解决办法]
原因是输入玩数字后输入缓冲区stdin里保留了\n,而\n也本认为是一个字符。
你可以调用fflush(stdin)清空输入缓冲区,使其为空,这是就会正常了。
[解决办法]
在后三个printf前一行加fflush(stdin);就可以了。
[解决办法]
scanf()函数是从输入流缓冲区中读取值的,而并非从键盘(也就是终端)缓冲区读取。
pls input the value of a:4
pls input the value of b:5
pls input the value of c:6 //在你输入了6之后,肯定敲入了回车,然后这个回车会在缓冲区中。下一个scanf就直接从缓冲区中读取了字符 回车 ,缓冲区被读取完了,等下一个的读取。
pls input the chara m:pls input the chara n:7(他一次性打印出来两行)
pls input the chara i:$(这里不等我输入就结束运行了)
TO 3L,那个好像是C++的标准,C语言没有,我试了下在GCC编译器不起作用。建议用getchar()来把回车取出来,也就是清除了缓冲区。不过,这个还有个bug,你在输入a,b,c的时候,你输入个字母看看,有什么情况。
#include<stdio.h>int main(void){ int a,b,c; char m,n,i; printf("pls input the value of a:"); scanf("%d",&a); printf("pls input the value of b:"); scanf("%d",&b); printf("pls input the value of c:"); scanf("%d",&c); printf("pls input the chara m:"); getchar() ; scanf("%c",&m); printf("pls input the chara n:"); getchar(); scanf("%c",&n); printf("pls input the chara i:"); getchar() ; scanf("%c",&i); return 0;}