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