Search code examples
cloopswhile-loopscanfstdin

Passing string when program expect int in C


I have the following code:

#include <stdio.h>

int main(){

    int a;

    while(1)
    {
        scanf("%d", &a);
        if(a >= 1000000 || a <= 9999)
        {
            printf("Error");
        }
        else
        {
            break;
        }
    }

return 0;
}

I would expect the user to type something like 20201 and if it was an invalid input it would start again but I notice that when I type 2020.1 the program returns:

ErrorErrorErrorErrorErrorErrorError...

And keeps looping forever and never ask the number again, why is this happening? Isn't the code suppose to print just one error message and wait for the input again in scanf?


Solution

  • Yes, it is supposed to. However, here, when the matching failure happens (due to the presence of . in the input), the input remains in the input buffer, and fed to next invocation of scanf(), only to fail again, thus going in infinite loop.

    You need to clear the input buffer of the invalid input, after a failure has happened. For that, you must check the return value of scanf() to ensure a successful scanning.