getc(fp) causing trouble

一笑奈何 提交于 2019-12-25 05:10:04

问题


Here is my code.

#include<stdlib.h>
#include<stdio.h>
int main(int argc,char** argv)
{
    char a;
    a=9;
    FILE * fp;
    fp=fopen(argv[1],"r");
    while(a!= EOF)
    {
        a=fgetc(fp);
        printf("\n%d",a);
    }
}

The output to this is alright but at the end I am getting a weird character with -1 (since I am printing integer value.

How to stop it at EOF only? Also what is this character?


回答1:


Besides the methods in the other answers, you can also do like this:

while ((a = fgetc(fp)) != EOF)
{
    printf("%d\n", a);
}

Now you have a few alternative solutions. :)

Edit: As R.. so kindly reminds us, you also have to change the type of a to int.




回答2:


You are printing the EOF character (the -1) as you do not check if EOF was encountered immediately after fgetc(). Change the structure of the loop to:

int a; /* not char, as pointed out by R... */

for (;;)
{
    a = fgetc(fp);
    if (EOF == a) break;
    printf("\n%d", a):
}



回答3:


You need to make a have type int, as that type is the return type of fgetc(), and is needed to represent EOF correctly.




回答4:


Why don't you stop the while with this condition:

do {...}while(a != EOF)

I suppose that a got EOF value AFTER read it. So, you do the cycle an extra time



来源:https://stackoverflow.com/questions/9378073/getcfp-causing-trouble

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!