比较无符号的字符和EOF [英] Comparing unsigned char and EOF

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

问题描述

在以下code编译它进入一个无限循环:

when the following code is compiled it goes into an infinite loop:

int main()
{
    unsigned char  ch;
    FILE *fp;
    fp = fopen("abc","r");
    if(fp==NULL)
    {
        printf("Unable to Open");
        exit(1);
    }
    while((ch = fgetc(fp))!=EOF)
    printf("%c",ch);
    fclose(fp);
    printf("\n",ch);
    return 0;
}

gcc编译器还提供了有关编译警告

The gcc Compiler also gives warning on compilation

abc.c:13:warning: comparison is always true due to limited range of data type

在code运行良好时, unsigned char型字符替换或 INT 如预期,即它终止。结果
但是,code也运行正常为 unsigned int类型为好。
因为我有我的 EOF 已经阅读被定义为 1 stdio.h中那么为什么这code失败unsigned char型,但运行良好的unsigned int类型。

the code runs fine when unsigned char is replaced by char or int as expected i.e. it terminates.
But the code also runs fine for unsigned int as well. as i have i have read in EOF is defines as -1 in stdio.h then why does this code fails for unsigned char but runs fine for unsigned int.

推荐答案

写这行的金科玉律是

   while ((ch = fgetc(stdin)) != EOF)

CH INT 。你的制作可爱绝招 CH 无符号的失败,因为 EOF 是一个符号整数数量。

ch should be int .Your cute trick of making ch unsigned fails because EOF is a signed int quantity.

好吧,现在让我们进入深度......

Ok, let's now go into the depth......

第1步:

ch=fgetc(fp)

龟etc()收益 1 (签署的 INT )。采用C CH 的金科玉律得到位的最后一个字节是所有 1 的。因此值 255 。执行后 CH 的字节模式

fgetc() returns -1 (a signed int). By the golden rules of C ch gets the last octet of bits which is all 1's. And hence the value 255. The byte pattern of ch after the execution of

ch = fgetc(fp); 

因此​​是

11111111

第二步:

ch != EOF

现在 EOF 符号整数 CH unsigned char型 ...

Now EOF is a signed integer and ch is an unsigned char ...

我再次引用C的金科玉律......小家伙的 CH 转换为大尺寸的 INT 对比之前,所以它的字节模式现在是

Again I refer to the golden rule of C ... the smaller guy ch is converted to big size int before comparision so its byte pattern is now

00000000000000000000000011111111 = (255)10

,而 EOF

11111111111111111111111111111111 = (-1)10

有没有办法,他们可以等于.......因此,声明引导下while循环

There is no way they can be equal....... Hence the statement to steer the following while-loop

while ((ch = fgetc(stdin)) != EOF)

将永远不会为false ...

will never evaluate to false ...

和因此而无限循环。

这篇关于比较无符号的字符和EOF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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