更新时间:2015-10-31 22:49:14浏览次数:1+次
#include<stdio.h>
int main()
{
int a;
printf("input the data\n");
scanf("%d\n",&a);//这里多了一个回车符\n
printf("%d",a);
return 0;
}
结果要输入两个数程序才结束,而不是预期的一个。why?#include<stdio.h>
int main()
{
int n = 5;
char c[n];
for(int i = 0; i < n; i++)
c[i] = scanf("%c",&c[i]);
printf(c);
return 0;
}
如果输入:解决方法:把程序改成这样就可以了:
for( i = 0; i < n; i++){
scanf("%c",&c[i]);
fflush(stdin);//刷新缓冲区
}
或者不用scanf,而用gets()函数,如:
#include<stdio.h>
int main()
{
char c[5];
gets(c);
printf(c);
return 0;
}
#include<stdio.h>
int main()
{
int a=123;
char c='t';
printf("input\n");
scanf("%d%c",&a,&c);
scanf("%d%c",&a,&c);
scanf("%d%c",&a,&c);
printf("%d\n%c\n",a,c);
return 0;
}
当输入a 回车 后,会直接跳过下面2个scanf语句,直接输出为#include <stdio.h>
int main()
{
int a=123,b=1;
char c='t';
scanf("%d%d",&a,&b);
scanf("%c",&c);
printf("%d\n%d\n%c\n",a,b,c);
return 0;
}
输入:2 回车a 回车
结果是:#include <stdio.h>
main()
{
int a=123,b;
while(scanf("%d%d",&a,&b)!=2)
fflush(stdin);
printf("%d\n%d\n",a,b);
return 0;
}
你可以试一下,如果输入不是数字时,会有什么反应。
#include<stdio.h>
int main()
{
char strings[100];
scanf("%[1234567890]",strings);
printf("%s",strings);
return 0;
}
运行,输入:1234werew后,结果是:1234。相关资讯