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

后端 未结 16 1493
日久生厌
日久生厌 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条回答
  •  Happy的楠姐
    2020-11-21 07:13

    I had similar problem. I solved by only using scanf.

    Input "abc123" to see how it works.

    #include 
    int n, num_ok;
    char c;
    main() {
        while (1) {
            printf("Input Number: ");
            num_ok = scanf("%d", &n);
            if (num_ok != 1) {
                scanf("%c", &c);
                printf("That wasn't a number: %c\n", c);
            } else {
                printf("The number is: %d\n", n);
            }
        }
    }
    

提交回复
热议问题