【发布时间】:2013-02-14 09:05:13
【问题描述】:
第一次工作,第二次执行时跳过第二个scanf函数。从几页谷歌之后,注意到这是在缓冲中添加 \n 的 scanf 函数的行为,为了解决这个问题,我在 scanf 之后添加了 fflush(stdin) 并且它确实有效,但是当第二次执行时,它给我一个错误的结果。有人可以指导我这个程序的问题是什么?
#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;
}
【问题讨论】:
-
在您读取输入之后检查长度 几乎没有用。但是,您可以告诉
scanf最多获取特定数量的字符,其格式为"%50s"。 -
阅读
scanf返回值的含义,并检查它是否存在解析错误...在排除使用scanf的任何代码的问题之前,没有多大意义无效输入(或无效格式字符串,取决于您的观点)的简单可能性。
标签: c