初级程序员在这里学习C
我的部分代码要求用户输入数字,然后进入 while 循环检查输入的值是否为数字,如果不是,while 循环将清除输入(以停止无限循环),并询问再次询问号码。
问题是,当我清除输入然后在 while 循环中再次请求 scanf() 时,它显然清除了两次,我必须再次输入数字才能得到我的结果。
这里是有问题的部分代码:
int askNum()
{
int number;
int check;
printf("Enter a number: ");
check = scanf("%d", &number);
while(scanf("%d", &number) != 1)
{
printf("You've entered an incorrect number.\nEnter a number: ");
fflush(stdin);
check = scanf("%d", &number);
}
return number;
}
如果有人可以解释为什么这样做,请解释或给我一些关于如何进行的提示。
非常感谢!
最佳答案
因为你的 while() 是错误的。
此外,fflush() 仅针对输出流定义。如果你想要可移植的代码,你应该这样做:
void fpurge(FILE *pf)
{
int c;
while((c=fgetc(pf)) != '\n' && c != EOF)
{ }
}
它将可靠地读取字符直到行尾。
关于c - 为什么 fflush(stdin) 在 while 循环中执行两次以检查 scanf() 输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23942012/