为什么我没有得到 EOF?

Why I don't get the EOF?

这是我的代码示例。我在评论中写下了问题:

main(){
    long cnt; // chars count
    int c;

    /* Why the 'for' cicle doesn't finish when I input the
     * "a^Z" string and press ENTER? At this case '^Z' is
     * CTRL + Z (i.e this is EOF). I expected the second loop
     * will get the EOF (i.e. -1), but it has 26 instead of. Why?
     */
    for(cnt = 0; (c = getchar()) != EOF; ++cnt)
        ;

    printf("Chars count: %ld", cnt);
}

如果我输入 aENTERCTRL + ZENTER,那么我会得到预期的结果:CTRL + Z 打破循环。

UPD

当我阅读有关 getchar 函数的信息时,我看到它使用 行缓冲输入 。它期望 ENTER 用于推送数据。我没有看到它 可以在获得 Ctrl - Z 时推送数据的信息。因此,我预计在我的情况下第二个值将是 EOF(并且循环将被打破),即我预计我的字符串行将像 aEOF 一样被解析\n序列。

当你按下 a+ CTRL + Z 然后按下 ENTERCTRL + Z刷新输入(stdin),下一个输入是\n,这不是 EOF。需要按CTRL+Z两次模拟第二个EOF.