它第一次工作,当第二次执行时,它跳过第二个scanf函数。谷歌从几个页面后,注意到这是scanf函数的行为,在缓冲区中添加\ n,为了解决这个问题,我在scanf之后添加了fflush(stdin),但它确实起作用,但是当它在第二次执行时,它给我一个错误的结果。有人可以指导我这个计划的问题是什么?C扫描循环
#include <stdio.h>
#include <stdlib.h>
int main()
{
char UserInput[50];
int i = 0;
int exit;
do{
printf("Please enter a string (less than 50 character): ");
scanf("%[a-z,A-Z, ,]s",&UserInput);
while(UserInput[i] != '\0' && i<50)
{
i++;
}
if (i==50)
printf("The string is too long\n");
else
printf("The length of the string is %d\n",i);
printf("To continue, please key in any numbers other than 0: ");
scanf("%d",&exit);
fflush(stdin);
}while(exit !=0);
system("PAUSE");
return 0;
}
检查长度_after_读取输入是非常没用的。但是,您可以通过''%50s'''等格式告诉'scanf'获取最多特定数量的字符。 – 2013-02-14 09:08:50
阅读'scanf'返回值的含义,并检查它是否存在解析错误...在使用'scanf'试图找出任何代码出现问题之前没有太多意见,直到您排除了无效输入的简单可能性(或无效的格式字符串,这取决于你的观点)。 – hyde 2013-12-06 00:22:26