一. 遇到的情况
在多次使用scanf函数时常常会出现下面的情况:
1.
运行下列代码:
#include<stdio.h>
int main()
{
int a,b,c,x,y,z;
scanf("%d,%d,%d",&a,&b,&c);
scanf("%c%c%c",&x,&y,&z);
printf("%d,%d,%d\n",a,b,c);
printf("x=%c,y=%c,z=%c\n",x,y,z);
return 0;
}
(1)有关回车(Enter)
从键盘中输入:
11,12,13
按回车(Enter)后输入:
ABC
按回车(Enter)后运行结果为:
(2)有关空格
从键盘中输入(含空格):
11,12,13 ABC
按回车(Enter)后运行结果为:
2.
运行下列代码:
#include<stdio.h>
int main()
{
int a,b,c,x,y,z;
scanf("%d,%d,%d",&a,&b,&c);
scanf("x=%d,y=%d,z=%d",&x,&y,&z);
printf("%d,%d,%d\n",a,b,c);
printf("x=%d,y=%d,z=%d\n",x,y,z);
return 0;
}
(1)有关回车(Enter)
从键盘中输入:
11,12,13
按回车(Enter)后运行结果为:
(2)有关空格
从键盘中输入(含空格):
11,12,13 x=14,y=15,z=16
按回车(Enter)后运行结果为:
很明显上面几种情况的运行结果与预期结果不符
二.原因
(1)有关回车
当用户在输入数据时按下回车键,scanf函数会将回车符作为输入字符之一,并将其吸收到缓冲区中。如果后续的scanf函数读取字符时遇到了回车符,它会将其作为输入字符之一,而不是将其作为输入结束语。
(2)有关空格
在后续的scanf函数需要读取字符时,scanf函数会把空格作为输入字符之一。
三.解决办法(以第一种情况为例)
1.加空格
可以抵消输入的回车或满足scanf函数使用要求。
int main()
{
int a,b,c,x,y,z;
scanf("%d,%d,%d",&a,&b,&c);
scanf(" %c%c%c",&x,&y,&z);
printf("%d,%d,%d\n",a,b,c);
printf("x=%c,y=%c,z=%c\n",x,y,z);
return 0;
}
运行结果:
2.数字后紧接字母
数字后紧接字母,不要空格也不要回车。因为数字和字母是能够被区分开来的。
int main()
{
int a,b,c,x,y,z;
scanf("%d,%d,%d",&a,&b,&c);
scanf("%c%c%c",&x,&y,&z);
printf("%d,%d,%d\n",a,b,c);
printf("x=%c,y=%c,z=%c\n",x,y,z);
return 0;
}
从键盘中输入:
11,12,13ABC
运行结果:
3.将需读取字母的scanf函数放到最前面
#include<stdio.h>
int main()
{
int a,b,c,x,y,z;
scanf("%c%c%c",&x,&y,&z);
scanf("%d,%d,%d",&a,&b,&c);
printf("%d,%d,%d\n",a,b,c);
printf("x=%c,y=%c,z=%c\n",x,y,z);
return 0;
}
运行结果:
4.使用getchar();
使用scanf函数后使用
getchar();
。可以清除输入缓冲区中的回车符或清除空格。
#include<stdio.h>
int main()
{
int a,b,c,x,y,z;
scanf("%d,%d,%d",&a,&b,&c);
getchar();
scanf("%c%c%c",&x,&y,&z);
printf("%d,%d,%d\n",a,b,c);
printf("x=%c,y=%c,z=%c\n",x,y,z);
return 0;
}
运行结果:
5.使用fflush(stdin)函数
使用scanf函数后使用
fflush(stdin)
函数。可清除输入缓冲区,避免回车对后续读取字符的影响。(无法清除空格)
#include<stdio.h>
int main()
{
int a,b,c,x,y,z;
scanf("%d,%d,%d",&a,&b,&c);
fflush(stdin);
scanf("%c%c%c",&x,&y,&z);
printf("%d,%d,%d\n",a,b,c);
printf("x=%c,y=%c,z=%c\n",x,y,z);
return 0;
}
运行结果:
6.使用while(getchar()!='\n');
使用scanf函数后加上
while(getchar()!='\n');
。可以清除输入缓冲区中的回车符。(无法清除空格)文章来源:https://www.toymoban.com/news/detail-740584.html
#include<stdio.h>
int main()
{
int a,b,c,x,y,z;
scanf("%d,%d,%d",&a,&b,&c);
while(getchar()!='\n');
scanf("%c%c%c",&x,&y,&z);
printf("%d,%d,%d\n",a,b,c);
printf("x=%c,y=%c,z=%c\n",x,y,z);
return 0;
}
运行结果:文章来源地址https://www.toymoban.com/news/detail-740584.html
到了这里,关于【C语言】连续使用多个scanf函数时输入数据的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!