为什么我没有得到EOF?
这是我的代码示例。我写在我的评论的问题:为什么我没有得到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
序列。
当按下一个 + CTRL + Ž然后按ENTER,所述CTRL + Ž冲输入(stdin
)和下一个输入是\n
,这不是一个EOF
。您需要按CTRL + Z两次模拟第二个EOF
。
我还是不明白......'\ n'值是'10',但是我得到了'26'。 –
@AndreyBushman你如何检查? –
我在MS Visual Studio的* Watch *窗口中查看值。 –
为什么你在循环后得到一个分号? – byxor
@BrandonIbbotson使用循环限制增加'cnt'。 –
@SouravGhosh有道理。谢谢。 – byxor