Why this example is stuck in an infinite loop in C? [duplicate]

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-02 11:07:28

The reason that you are getting infinite loop on entering a non-digit is the non-digit character left in the buffer as it is not read by the scanf for the next read of scanf (as it doesn't matches the format specifier). on next iteration scanf again finds this character and do not read it and exit immediately. This happens repeatedly and you are getting an infinite loop. Place a while(getchar() != '\n'); statement to consume this character.

Try this

#include <stdio.h>

int main(int argc, const char * argv[]) {

    int number = 0, isnumber;
    getagin: printf("Please enter a number:\n");
    isnumber = scanf("%i", &number);
    if(isnumber) {
        printf("You enterd a number and it was %i\n", number);
    } else {
        printf("You did not eneter a number.\n");
        while(getchar() != '\n'); // T consume all non-digits
        goto getagin;
    }

    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!