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

后端 未结 16 1457
日久生厌
日久生厌 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:53

    // all you need is to clear the buffer!
    
    #include 
    
    int main()
    {
        int number, p = 0, n = 0;
        char clearBuf[256]; //JG:
        while (1) {
            printf("-> ");
            if (scanf("%d", &number) == 0) {
                fgets(stdin, 256, clearBuf); //JG:
                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;
    }
    

提交回复
热议问题