使用c语言中标准输入函数scanf()输入字符的注意事项,涉及缓存区的原理,并用fflush()函数解决出现的问题

1、输入产生错误的代码

#include<stdio.h>
int main()
{
    
    
	int a,b;
	float c,d;
	char x,y;
		scanf("%d%d",&a,&b);
		printf("%d,%d\n",a,b);
		scanf("%f%f",&c,&d);
		printf("%f,%f\n",c,d);//fflush(stdin);
		scanf("%c,%c",&x,&y);
		printf("%c,%c\n",x,y);
		
	return 0;

}

执行结果(输入字符’w’,'e’时产生错误):在这里插入图片描述

2、为什么会产生上面的错误

这涉及到标准输入的缓存机制,在命令行中输入的数据放在缓存区中:
(1)、在执行scanf("%f%f",&c,&d);中,我输入了2.3和4.21,并回车执行,于是缓存区中buffer[] ={2.3,4.21,’\n’};
(2)、执行printf("%f,%f\n",c,d);后2.3和4.21被读取出缓存;
(3)、执行scanf("%c,%c",&x,&y);后buffer[]={’\n’ , ‘w’ , ‘,’ , ‘e’};
(4)、执行printf("%c,%c\n",x,y);,从缓存区中读取的并不是字符’w’和’e’,所以出错,显示为 ,? ;

3、改进后输出正确的代码

这涉及到fflush(stdin)函数,
fflush(stdin)函数德尔作用为:把缓存区中的数据写入对应的变量或文件,然后清空缓存。(空的缓存区便能正确的接收用scanf()输入的字符,然后正确输出。)

正确代码如下:

#include<stdio.h>
int main()
{
    
    
	int a,b;
	float c,d;
	char x,y;
		scanf("%d%d",&a,&b);
		printf("%d,%d\n",a,b);
		scanf("%f%f",&c,&d);
		printf("%f,%f\n",c,d);fflush(stdin);
		scanf("%c,%c",&x,&y);
		printf("%c,%c\n",x,y);
		
	return 0;

}

执行结果:在这里插入图片描述

4、参考资料

C语言中的输入输出流和缓冲区:
https://blog.csdn.net/tonglin12138/article/details/85534308

https://www.jb51.net/article/147882.htm

猜你喜欢

转载自blog.csdn.net/txt666999999/article/details/109038478