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

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

    Rather than using scanf() and have to deal with the buffer having invalid character, use fgets() and sscanf().

    /* ... */
        printf("0 to quit -> ");
        fflush(stdout);
        while (fgets(buf, sizeof buf, stdin)) {
          if (sscanf(buf, "%d", &number) != 1) {
            fprintf(stderr, "Err...\n");
          } else {
            work(number);
          }
          printf("0 to quit -> ");
          fflush(stdout);
        }
    /* ... */
    

提交回复
热议问题