2016-12-08 80 views
1

这是我的代码示例。我写在我的评论的问题:为什么我没有得到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(并且循环将被打破),即我预计我的字符串行将被解析,如a,EOF,\n序列。

+0

为什么你在循环后得到一个分号? – byxor

+2

@BrandonIbbotson使用循环限制增加'cnt'。 –

+0

@SouravGhosh有道理。谢谢。 – byxor

回答

1

当按下一个 + CTRL + Ž然后按ENTER,所述CTRL + Ž冲输入(stdin)和下一个输入是\n,这不是一个EOF。您需要按CTRL + Z两次模拟第二个EOF

+0

我还是不明白......'\ n'值是'10',但是我得到了'26'。 –

+1

@AndreyBushman你如何检查? –

+0

我在MS Visual Studio的* Watch *窗口中查看值。 –