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

无人久伴 提交于 2019-12-02 03:09:51

问题


I am using what scanf() returns when it gets what is expects or when it doesn't. What happens is it gets stuck in thewhile()` loop.

To my knowledge test = scanf("%d", &testNum); returns a 1 if it receives a number and a 0 if not.

My code:

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

回答1:


The problem here is, upon encountring an invalid input, (a character, for example), the incorrect input is not consumed, it remains in the input buffer.

So, in the next loop, the same invalid input is again read by scanf().

You need to clean up the buffer after identifying incorrect input. A very simple approach will be,

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

That said, either initialize test, or remove printf("%d", test);, as test being an automatic variable, unless initialized explicitly, contains indeterminate value. Attempt to use that can invoke undefined behavior.

That said, just to be nit-picky, return is not a function, don't make it look like one. It's a staement, so return 0; is much more soothing to the eyes and much less confusing, anyway.



来源:https://stackoverflow.com/questions/39537753/why-inside-a-loop-scanf-with-d-does-not-wait-for-the-user-input-in-case-it-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!