【问题标题】:datatype of variable used for holding input of getchar(),as char instead of int用于保存 getchar() 输入的变量的数据类型,作为 char 而不是 int
【发布时间】:2014-08-14 10:05:11
【问题描述】:
#include<stdio.h>

int main()

{


    int c;

    while((c=getchar())!=EOF)
       putchar(c);
    putchar(c);     //2nd putchar     
    getch();


}

在“Ritchie n Kernighan 的 C”一书中的上述代码中,声明 cint 变量的原因如下:

这样c 可以保存EOF 的代码,该代码在char 数据类型可以容纳的字符代码之外。

但是当我将 c 声明为 char 并输入 EOF(CTRL-Z + Enter) 时,该值(在我的计算机上为 -1)确实进入 c,我立即退出 while up ,就像我将 c 声明为 int 时那样。 为什么我们需要将 c 声明为 int,而 char 工作得很好?还是我在这里遗漏了什么?

还有一件事,在第二个putchar 语句中,它应该在收到EOF 之后打印c 的最后一个值(即-1),但它没有。为什么?

【问题讨论】:

  • 让任何说荷兰语的人无法接触到您的程序。其中 ij 有向字母是一个普通字母,通常使用字符代码 255。没什么大问题,我们只有 2500 万。
  • 在最后一段中解决您的问题:在putchar 打印一个值之前,它会将其转换为unsigned char。所以,假设EOF 是-1(它不是必须的,但最常见的是),转换为(8 位)unsigned char 产生0xFF,根据您的编码,可能是什么是否为有效字符(例如,在 UTF-8 中,此字节不能以任何有效序列出现)。所以也许你只是没有看到它,虽然它是输出的。通过hexdump 管道输出或将其写入文件。
  • 这是一个启示! @HansPassant

标签: c getchar kernighan-and-ritchie


【解决方案1】:

char 是有符号还是无符号是实现定义的。

如果char是无符号的,那么没有char的值可以等于EOF,循环永远不会退出。

如果char 已签名,那么EOF 可能等于c,这就是在您的机器上发生的情况。但问题是,这也意味着有效的char 可能等于EOF,导致循环退出过早。

【讨论】:

    【解决方案2】:
    But when I declare c as a char, and input the EOF(CTRL-Z + Enter),that 
    value(which is -1 on my computer)does go into c and I immediately end up 
    exiting the while up, just the way it happens if I declare c as an int.
    

    回想一下,getchar 相当于getc(stdin)。当您到达eof 时,该条件设置在stdin 上,您在循环中的测试将不再为真。因此,无论您使用 int、char 还是 unsigned char,循环都会终止。

    One more thing, in the second putchar statement, it should print the 
    last value of c (ie. -1) after having received EOF but it doesn't. Why?
    

    出于同样的原因,到达EOF,循环终止而不调用putchar。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-04
      • 2022-01-13
      • 1970-01-01
      • 2013-08-03
      • 2019-07-23
      • 2015-10-11
      • 1970-01-01
      相关资源
      最近更新 更多