Why inside a loop, scanf() with

后端 未结 1 632
遥遥无期
遥遥无期 2021-01-22 13:16

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 t

相关标签:
1条回答
  • 2021-01-22 13:39

    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.

    0 讨论(0)
提交回复
热议问题