EOF符号常量 [英] EOF symbolic constant
问题描述
从的 C程序设计语言的:
INT℃;
而((C =的getchar())!= EOF)
的putchar(C);
......解决方法是的getchar
时,有没有更多的投入,不能与任何真实人物相混淆的值返回一个独特的价值,这个价值是名为 EOF
,为文件结束。我们必须申报 C
是一个类型的大到足以容纳任何值该的getchar
的回报。我们不能用字符
,因为 C
必须足够大,以容纳 EOF
除了任何可能的字符
。
我 stdio.h中
检查并印在我的系统EOF的值,它被设置为 1
。在我的系统,字符
签署,虽然我明白,这是取决于系统。因此, EOF
可适合在字符
我的系统。我重写了小例行上述定义 C
是一个字符
和预期的程序工作。还有这里的ASCII字符表一个字符,似乎有相应的255个空白字符这似乎像 EOF
。
那么,为什么它似乎ASCII有指定EOF字符(255)?这似乎矛盾的时候,在说的 C程序设计语言的书。
那么,为什么它似乎ASCII有指定EOF字符(255)?
块引用>它没有。更多precisely,那不是EOF字符
诀窍是,
的getchar()
总是返回非负值,如果有东西可以读。它只会返回1
(这是EOF
出现在您的实现定义的),如果它遇到结束-file。事实上,
字符
是:
- 8位宽,
- 签名和
- 使用2的补再presentation,
只是你的实现怪癖(虽然绝大多数时下常见)。因此,如果您使用的是
。字符
存储的返回值的getchar()
,然后读取输入可以终止prematurely:与code 255的字符会被误认为是-1。 ķ。一个。EOF
,这是一个错误。这正是发生在你身上。 它没有工作 - 相反,你的第二个方法是彻底打破From The C Programming Language:
int c; while ((c = getchar()) != EOF) putchar(c);
"... The solution is that
getchar
returns a distinctive value when there is no more input, a value that cannot be confused with any real character. This value is calledEOF
, for "end of file." We must declarec
to be a type big enough to hold any value thatgetchar
returns. We can't usechar
sincec
must be big enough to holdEOF
in addition to any possiblechar
."I checked in
stdio.h
and printed the value of EOF on my system, and it's set to-1
. On my system,chars
are signed, although I understand that this is system dependent. So,EOF
can fit in achar
for my system. I rewrote the small routine above by definingc
to be achar
and the program works as intended. There's also a character in the ASCII character table here that appears to have a blank character corresponding to 255 which appears to act likeEOF
.So, why does it appear that ASCII has a character (255) designated for EOF? This seems to contradict what is said in the The C Programming Language book.
解决方案So, why does it appear that ASCII has a character (255) designated for EOF?
It hasn't. More precisely, that's not the EOF "character".
The trick is,
getchar()
will always return non-negative values if it has something to read. It will only return-1
(that's whatEOF
appears to be defined on your implementation) if it encounters end-of-file.The fact that
char
is:
- 8 bits wide,
- signed and
- uses a 2's complement representation,
is just a quirk of your implementation (although overwhelmingly common nowadays). Thus, if you are using a
char
to store the return value ofgetchar()
, then reading the input may terminate prematurely: the character with code 255 will be mistaken for -1 a. k. a.EOF
, which is an error. This is just what happened to you. It didn't work -- conversely, your second approach was completely broken.这篇关于EOF符号常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!