当我扫描一个数字时,为什么我的int while循环继续运行?

时间:2014-04-25 11:30:00

标签: c while-loop scanf

我遇到了while循环问题。我必须输入一个大于0且低于81的数字。当我使用-1,0,1,2,82这样的数字时它会很好并且我得到预期的结果,但是当我使用一封信时它会继续通过我的while循环。我在eclipse中使用了调试器,当我在while循环中amount自动设置为' 0'因为scanf失败了。插入字母时为什么会循环?

eclipseDebug

#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;
}

2 个答案:

答案 0 :(得分:4)

您需要确保scanf()有效。使用返回的值来执行该操作

if (scanf("%d", &amount) != 1) /* error */;

当它不起作用时(因为例如在输入中找到了一个字母)你可能想要摆脱错误的原因。

从用户那里获得输入的更好选择是使用fgets()

答案 1 :(得分:1)

请参阅此相关问题:scanf() is not waiting for user input

原因是当你用一个字符输入enter时,scanf失败并且没有吃掉输入提要中的字符。结果,下一个块开始具有您之前输入的任何内容。

您可以在getchar()循环内的scanf()之前添加while来检查。您会注意到它会重复while循环,因为您的行有无效字符,然后停止并等待输入。每次循环运行时,getchar()都会在输入中吃掉一个无效字符。

但最好不要那样使用scanf。看看这个资源: Reading a line using scanf() not good?