0

I've written the code down below to read some values from a text file and then find the average of those numbers but for some reason when it is in the while loop, it doesn't see where the file ends and keeps on adding them together forever. I'd really appreciate if you could tell me why that happens and how I can get out of it. Thank you.

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

main(){
int total, grade, n;
float a;

total = 0;
n = 0;

FILE *file;
file = fopen("grades.txt", "r");

if( (file = fopen("grades.txt", "r")) == NULL) {
    puts("Error");
    exit(0);
}   
while (!(feof(file))) {
    if (!(fscanf(file, "%d",&grade) ==-1 )){
        total = total + grade;
        n++;
        printf("%d\n", total);
    }       
    else {
        break;
    }
}   
fclose(file);
a = total / n;
printf("The average is %f", a);
getch();
}

2 Answers2

3

Your code has no problem handling the end of file, but it has another problem, which prevents the loop from terminating: when scanf returns zero, because there was no valid input for it to process, the loop continues running forever.

Change the condition to stop the loop when scanf returns anything other than 1 to fix this problem.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thank you for your answer but it turns out what I did works too. I also asked a friend of mine and he pointed out that my problem was in text file, not in the code. The numbers in my file were floats while my code was looking for integers. So when I changed them to integers, it somehow terminated when it should. – Eren O. Dec 22 '16 at 23:20
0

Change if (!(fscanf(file, "%d",&grade) ==-1 )) to if(fscanf(file,"%d",&grade) == 1) and try it. Or make else condition like if(grade == -1) break;