2

我正在使用什么scanf() returns when it gets what is expects or when it doesn't. What happens is it gets stuck in thewhile()` 循环。

据我所知test = scanf("%d", &testNum);,如果收到数字则返回 1,否则返回 0。

我的代码:

#include<stdio.h>

int main(void) {
    while (1) {
        int testNum = 0;
        int test;
        printf("enter input");
        test = scanf("%d", &testNum);
        printf("%d", test);
        if (test == 0) {
            printf("please enter a number");
            testNum = 0;
        }
        else {
            printf("%d", testNum);
        }
    }
    return(0);
}
4

1 回答 1

1

这里的问题是,在遇到无效输入(例如,一个字符)时,不正确的输入不会被消耗,它会保留在输入缓冲区中。

因此,在下一个循环中,相同的无效输入再次被scanf().

您需要在识别出不正确的输入后清理缓冲区。一个非常简单的方法是,

    if (test == 0) {
        printf("please enter a number");
        while (getchar() != '\n');  // clear the input buffer off invalid input
        testNum = 0;
    }

也就是说,初始化test或删除printf("%d", test);作为test自动变量,除非显式初始化,否则包含不确定的值。尝试使用它可以调用未定义的行为

也就是说,只是为了挑剔return不是一个功能,不要让它看起来像一个。无论如何,这是一种状态,因此return 0;对眼睛更舒缓,也不会令人困惑。

于 2016-09-16T18:18:27.750 回答