【发布时间】:2014-04-25 11:29:59
【问题描述】:
我在使用 while 循环时遇到了问题。我必须输入一个大于 0 且小于 81 的数字。当我使用像 -1,0,1,2,82 这样的数字时,它会很好并且我得到预期的结果,但是当我使用字母时它会继续通过我的while循环。我在 Eclipse 中使用了调试器,当我在 while 循环中时,amount 由于 scanf 失败而自动设置为“0”。为什么我插入一个字母时一直循环?
#include <stdio.h>
#include <stdlib.h>
int main(){
int amount = 0;
printf("Give a number:\n");
fflush(stdout);
scanf("%d",&amount);
while(amount <= 0 || amount >= 81){
printf("Wrong input try again.\n");
printf("Give a number:\n");
fflush(stdout);
scanf("%d",&amount);
}
return EXIT_SUCCESS;
}
【问题讨论】:
-
%d不用于信件。在while中验证之前,您需要将char输入转换为int。 -
使用错误的格式说明符是未定义的行为。
-
@Dayalrai 我明白了,但目前它将数量设置为 0。这是一个整数。所以它应该对我有效。对吗?
-
如果输入是一个字母,并且
amount设置为零,那么循环当然会继续,因为while子句的计算结果为真:while (amount <= 0 ||等于零。小提示:研究scanf存在的问题,并尽可能检查函数的返回值 -
您必须在使用扫描值之前检查
scanf()的返回值。它是 I/O,它可能会失败。不知道为什么这么多人在这方面失败了。
标签: c while-loop scanf