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

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

    Good evening. I've recently been through the same problem and i found a solution that might help a lot of guys. Well, actually the function "scanf" leaves a buffer at memory ... and that's why the infinite loop is caused. So you actually have to "store" this buffer to another variable IF your initial scanf contains the "null" value. Here's what i mean:

    #include 
    int n;
    char c[5];
    main() {
        while (1) {
            printf("Input Number: ");
            if (scanf("%d", &n)==0) {  //if you type char scanf gets null value
                scanf("%s", &c);      //the abovementioned char stored in 'c'
                printf("That wasn't a number: %s\n", c);
            }
            else printf("The number is: %d\n", n);
        }
    }
    

提交回复
热议问题