Why is scanf() causing infinite loop in this code?

后端 未结 16 1462
日久生厌
日久生厌 2020-11-21 06:20

I\'ve a small C-program which just reads numbers from stdin, one at each loop cycle. If the user inputs some NaN, an error should be printed to the console and the input pro

16条回答
  •  执念已碎
    2020-11-21 06:58

    The Solution: You need to add fflush(stdin); when 0 is returned from scanf.

    The Reason: It appears to be leaving the input char in the buffer when an error is encountered, so every time scanf is called it just keeps trying to handle the invalid character but never removing it form the buffer. When you call fflush, the input buffer(stdin) will be cleared so the invalid character will no longer be handled repeatably.

    You Program Modified: Below is your program modified with the needed change.

    #include 
    
    int main()
    {
        int number, p = 0, n = 0;
    
        while (1) {
            printf("-> ");
            if (scanf("%d", &number) == 0) {
                fflush(stdin);
                printf("Err...\n");
                continue;
            }
    
            if (number > 0) p++;
            else if (number < 0) n++;
            else break; /* 0 given */
        }
    
        printf("Read %d positive and %d negative numbers\n", p, n);
        return 0;
    }
    

提交回复
热议问题