2016-12-08 77 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 *窗口中查看值。 –