V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
Danswerme
V2EX  ›  问与答

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

  •  
  •   Danswerme · 2021-04-21 23:11:09 +08:00 · 586 次点击
    这是一个创建于 1101 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码如下,在第一步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);
    }
    
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   904 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 21:14 · PVG 05:14 · LAX 14:14 · JFK 17:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.