0

I have written this code to read from an input file and display the numbers:

#include<stdio.h>

int main()
{

    int i;
    FILE * f;
    f=fopen("inputA.txt","r");

    while (!feof(f)){
        fscanf(f, "%i", &i);
        printf("%i\t", i);
    }
    printf("\n");

}

The output shows the last number twice. I guess it is the problem of feof but I don't know how to solve it. Any ideas?

dragosht
  • 3,237
  • 2
  • 23
  • 32

1 Answers1

1
while( !feof(x) )

is incorrect.

You have to check the return value of fscanf() and only printf the i if the call was successful. If the fscanf() return value indicates an error, then you check feof() and break from the loop.

2501
  • 25,460
  • 4
  • 47
  • 87