0

这是我的代码。

#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);
    }
}

对此的输出没问题,但最后我得到了一个带有 -1 的奇怪字符(因为我正在打印整数值。

如何EOF仅止于它?还有这个角色是什么?

4

4 回答 4

2

您正在打印EOF字符(-1),因为您不检查是否EOF在 之后立即遇到fgetc()。将循环结构更改为:

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

for (;;)
{
    a = fgetc(fp);
    if (EOF == a) break;
    printf("\n%d", a):
}
于 2012-02-21T13:05:01.360 回答
2

除了其他答案中的方法外,您还可以这样做:

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

现在您有一些替代解决方案。:)

编辑:正如 R.. 提醒我们的那样,您还必须将类型更改aint.

于 2012-02-21T13:25:53.807 回答
1

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

于 2012-02-21T14:00:43.340 回答
0

你为什么不停止while这种情况:

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

我想在读取它之后获得了 EOF 值。所以,你做这个循环额外的时间

于 2012-02-21T13:05:11.477 回答