EOF符号常量 [英] EOF symbolic constant

查看:268
本文介绍了EOF符号常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从的 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。

事实上,字符是:


  1. 8位宽,

  2. 签名和

  3. 使用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 called EOF, for "end of file." We must declare c to be a type big enough to hold any value that getchar returns. We can't use char since c must be big enough to hold EOF in addition to any possible char."

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 a char for my system. I rewrote the small routine above by defining c to be a char 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 like EOF.

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 what EOF appears to be defined on your implementation) if it encounters end-of-file.

The fact that char is:

  1. 8 bits wide,
  2. signed and
  3. 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 of getchar(), 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆