首页 文章

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

提问于
浏览
0

我在eclipse中使用了调试器,当我在while循环时 amount 由于scanf失败而自动设置为'0' . 插入字母时为什么会循环?

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 回答

  • 1

    你需要确保 scanf() 有效 . 使用返回的值来执行此操作

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

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

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

  • 4

    看到这个相关的问题:scanf() is not waiting for user input

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

    您可以通过在 while 循环内的 scanf() 之前添加 getchar() 来检查 . 你'll notice that it' ll重复while循环,因为你的行有无效字符,然后停止并等待输入 . 每次循环运行时, getchar() 都会在输入中吃掉一个无效字符 .

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

相关问题