gpt4 book ai didi

c - 如何定义 `getchar()` 的返回类型?

转载 作者:行者123 更新时间:2023-11-30 20:45:57 25 4
gpt4 key购买 nike

这是代码:

#include <stdio.h>
int main()
{
char c;
while((c = getchar()) != EOF)
{
putchar(c);
}
return 0;
}

但是有人说我应该改变char cint c .

谁能告诉我原因?

最佳答案

因为 getchar() 定义为:

 int getchar(void);

这应该是足够的理由。原因解释的很好here :

如果将 getchar 的返回值分配给 char,则可能会出现两种类型的错误/失败。

If type char is signed, and if EOF is defined (as is usual) as -1, the character with the decimal value 255 ('\377' or '\xff' in C) will be sign-extended and will compare equal to EOF, prematurely terminating the input.

If type char is unsigned, an actual EOF value will be truncated (by having its higher-order bits discarded, probably resulting in 255 or 0xff) and will not be recognized as EOF, resulting in effectively infinite input.

关于c - 如何定义 `getchar()` 的返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33118645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com