EOF和普通整数有什么区别?
下面是代码
代码:
#include <stdio.h>
int main(void)
{
int ch;
while((ch = getchar()) != 'h')
putchar(ch);
return 0;
}
问题:
1.)像往常一样,我只是运行此代码,由于好奇,当程序提示输入时,我插入 ^ z(CTRL + Z)
这是 EOF(Windows 7 命令提示符)
,但我得到的只是无限循环的字符打印。
2.)从代码中,我的逻辑是,由于我向程序输入 ^z
,它只会评估逻辑 (ch = getchar()) != 'h'< /code> 和值
true
或 1
将被返回,字符 ^z
将被打印出来。但不同的结果是yield。
below is the code
Code :
#include <stdio.h>
int main(void)
{
int ch;
while((ch = getchar()) != 'h')
putchar(ch);
return 0;
}
Question :
1.)So as usual i just run this code , due to curiosity when the program prompt for input , i insert ^z(CTRL + Z)
which is EOF (Windows 7 Command Prompt)
, but all i get is infinite looping of character printing.
2.)From the code , my logic is that since i input ^z
to the program , it'll just evaluate the logic (ch = getchar()) != 'h'
and value true
or 1
will be returned and character ^z
will be printed out.But instead different result is yield.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您按
^Z
时,程序会注意到输入流已关闭,但您继续使用getchar()
,因此您会得到EOF
。这会无限循环,因为您无法再输入'h'
。请注意,仅'h'
(不是'A'
,也不是^M
,并且也不是^Z
)可以停止程序,因为如果没有得到“h”,则循环。换句话说,如果您想在输入除
'h'
之外的任何其他内容时停止,则执行以下操作When you press
^Z
, the program notices the input stream was closed, but you keep on usinggetchar()
, so you getEOF
. This loops infinitely, since you can't input'h'
anymore. Note that only'h'
(not'A'
, not^M
, and also not^Z
) can stop the program, since you loop if you don't get a 'h'.In other words, if you want to stop if anything else but
'h'
is entered, then doEOF 通常定义为 -1(但它是特定于实现的)。当您调用 putchar(-1) 时,它将转换为 unsigned char,并变为值 255,然后输出(除非我弄错了,否则)。
EOF is typically defined as -1 (but it's implementation specific). When you call putchar(-1), it will be converted to unsigned char, and become the value 255, which is then output (ÿ unless I'm mistaken).
EOF 是一个具有实现定义的负值的整数。您的代码无限循环,因为只有输入“h”才能完成。但是一旦它读取到 EOF,即
!= 'h'
,它就会进入无限循环,因为标准输入已关闭,没有任何东西可以让它返回任何其他内容。EOF is an integer with an implementation-defined negative value. Your code loops indefinitely because only entering 'h' would make it finish. But once it reads EOF, which is
!= 'h'
, it enters an infinite loop because the standard input is closed and there is nothing that can make it return anything else.