使用使用的feof的fscanf()() [英] Using fscanf() using feof()

查看:368
本文介绍了使用使用的feof的fscanf()()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的code。

#include<stdio.h>
void main(){
    FILE *fp;
    int a,b;
    fp=fopen("hello.txt","r");
    while(!feof(fp)){
      fscanf(fp,"%d %d",&a,&b);
      printf("%d %d\n",a,b);
    }
}

我的hello.txt的是

My hello.txt is

1   2
3   4

我的输出是

1   2
3   4
4   4

为什么正在打印我的最后一行两次。还没有达到FP EOF?

Why is my last line being printed twice. Has not fp reached EOF?

此外,在计算器的标记表示通常情况下,在使用时,使用它的code是错误的。
这是什么意思?

Also,the tag in stackoverflow says Usually, when it is used, the code using it is wrong. What does it mean?

感谢。

推荐答案

您必须永远不会立即检查其结果进行输入操作!

You must never perform an input operation without immediately checking its result!

下面应该工作:

while (fscanf(fp,"%d %d",&a,&b) == 2)
{
    printf("%d %d\n",a,b);
}

这将停止在该文件的第一次转换失败或结束。或者,您可以转换失败区分(跳过错误行)和档案结尾;看到的文档的fscanf

This will stop at the first conversion failure or end of the file. Alternatively, you could distinguish between conversion failures (to skip the erroneous line) and end-of-file; see the documentation of fscanf.

这篇关于使用使用的feof的fscanf()()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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