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

后端 未结 16 1458
日久生厌
日久生厌 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 07:04

    On some platforms (especially Windows and Linux) you can use fflush(stdin);:

    #include 
    
    int main(void)
    {
      int number, p = 0, n = 0;
    
      while (1) {
        printf("-> ");
        if (scanf("%d", &number) == 0) {
            fflush(stdin);
            printf("Err...\n");
            continue;
        }
        fflush(stdin);
        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;
    }
    

提交回复
热议问题