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

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

    Flush the input buffer before you scan:

    while(getchar() != EOF) continue;
    if (scanf("%d", &number) == 0) {
        ...
    

    I was going to suggest fflush(stdin), but apparently that results in undefined behavior.

    In response to your comment, if you'd like the prompt to show up, you have to flush the output buffer. By default, that only happens when you print a newline. Like:

    while (1) {
        printf("-> ");
        fflush(stdout);
        while(getchar() != EOF) continue;
        if (scanf("%d", &number) == 0) {
        ...
    

提交回复
热议问题