本文介绍了使用int作为字符类型与EOF进行比较时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Kernighan和Ritchie的C程序设计语言第16页引用 -

Quoting from Kernighan and Ritchie's 'The C Programming Language' Page 16 -

#include<stdio.h>

main()
{
int c;
c = getchar();

while(c!=EOF)
{
    putchar(c);
    c = getchar();
}

getchar();
return 0;
}

的类型字符专指用于存储这样的字符数据,但可以使用任何整数类型。我们使用 INT 的微妙而重要的原因。现在的问题是区分有效数据输入的结束。解决的办法是,的getchar 时,有没有更多的返回独特价值输入时,不能与任何真实人物相混淆一个值,该值被称为 EOF ,为文件结束,我们必须声明 C 是一个类型足够大,认为的getchar 的回报。我们不能用任何值字符,因为> C EOF 除了任何可能的字符。因此,我们使用 INT

"The type char is specifically meant for storing such character data, but any integer type can be used. We used int for a subtle but important reason. The problem is distinguishing the end of the input from valid data. 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. Therefore we use int.".

我在stdio.h抬头一看,上面写着的#define EOF(-1)

I looked up in stdio.h, it says #define EOF (-1)

这本书得出结论称字符不能使用,而这一计划工作得很好(请参阅​​编辑)与 C 字符数据类型为好。到底是怎么回事?在位,并签署价值方面任何人都可以解释一下吗?

The book conclusively states that char cannot be used whereas this program "works just fine" (See EDIT) with c as char data type as well. What is going on? Can anyone explain in terms of bits and signed values?

编辑:结果
由于奥利奇在答复中提到,该计划不能 EOF 255 区分。所以它不会正常工作。我想知道发生了什么 - 你是说,当​​我们做比较,C = EOF,EOF的值将被强制转换为字符值= 255(11111111二进制;!即位0 EOF的7写成2的补时符号)?


As Oli mentioned in the answer, the program cannot distinguish between EOF and 255. So it will not work fine. I want to know what's happening - Are you saying that when we do the comparison c!=EOF, the EOF value gets cast to a char value = 255 (11111111 in binary; i.e. the bits 0 through 7 of EOF when written in 2's complement notation)?

推荐答案

您程序不做工精细;这将无法 EOF 255

Your program doesn't work fine; it won't be able to distinguish between EOF and 255.

它似乎正常工作的原因是因为字符大概是签署你的平台上,因此它仍然能够再presenting 1

The reason it appears to work correctly is because char is probably signed on your platform, so it's still capable of representing -1.

这篇关于使用int作为字符类型与EOF进行比较时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 16:56