为什么在循环中,带有 %d 的 scanf() 不等待用户输入,以防它之前收到无效输入?

Why inside a loop, scanf() with %d does not wait for the user input in case it received an invalid input previously?

我正在使用 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); returns 如果收到数字则为 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);
}

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

因此,在下一个循环中,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 是一个自动变量,除非明确初始化,否则包含不确定的值。尝试使用可以调用 undefined behavior.

就是说吹毛求疵return不是一个函数,别弄成一个函数。这是一个 staement,所以 return 0; 对眼睛来说更舒缓,更不容易混淆,无论如何。