V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Danswerme
V2EX  ›  问与答

C 语言新手请教一个关于 EOF 的问题

  •  
  •   Danswerme · Apr 21, 2021 · 894 views
    This topic created in 1844 days ago, the information mentioned may be changed or developed.

    代码如下,在第一步getchar里如果输入了 EOF(我用的 macOS,输入了 Ctrl+D),那么循环里 scanf 就一直读不到值陷入死循环,用 rewind 清理掉 EOF 之后就没问题了,为什么第一个循环清理不掉 EOF 呢?

    #include <stdio.h>
    
    int main(void)
    {
        int ch;
        int num;
    
        ch = getchar();
    
        while ((ch = getchar()) != '\n' && ch != EOF)
            ;
    
        // rewind(stdin);
    
        while (scanf("%d", &num) != 1 || num < 1 || num > 5)
        {
            printf("%d\n", num);
        }
    
        printf("Number is %d\n", num);
    }
    
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2756 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 15:37 · PVG 23:37 · LAX 08:37 · JFK 11:37
    ♥ Do have faith in what you're doing.