這是我的代碼示例。我寫在我的評論的問題:爲什麼我沒有得到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);
}
如果我把a
,ENTER
,CTRL
+ Z
,ENTER
然後我得到預期的結果是:CTRL
+ Z
斷環。
UPD
當我讀到信息關於getchar
功能,然後我看到它使用行緩衝輸入。它期望ENTER
推送數據。我沒有看到信息,它也可以推動數據,當它得到Ctrl - Z
。因此,我預計在我的情況下,第二個值將是EOF
(並且循環將被打破),即我預計我的字符串行將被解析,如a
,EOF
,\n
序列。
爲什麼你在循環後得到一個分號? – byxor
@BrandonIbbotson使用循環限制增加'cnt'。 –
@SouravGhosh有道理。謝謝。 – byxor