Reputation: 23
#include <stdio.h>
int main()
{
FILE *fp;
char buffer[1001];
char name[15], surname[30];
float mid1, mid2, final, avg;
fp = fopen("grades.txt", "r");
if (!fp)
{
printf("Could not open file. Program finished.");
return 0;
}
fgets(buffer, 1000, fp);
while (feof(fp) == 0)
{
sscanf(buffer, "%s%s%f%f%f", name, surname, &mid1, &mid2, &final);
printf("%s %s %f %f %f\n", name, surname, mid1, mid2, final);
fgets(buffer, 1000, fp);
}
fclose(fp);
return 0;
}
Here is my text file,
Ali Veli 67 80 76
Ahmet Mehmet 45 64 63
Ayse Fatma 89 98 83
all the things okay but it can't read last line of the text file in the output "Ayse Fatma 89 98 83" it can't printing.
Upvotes: 1
Views: 479
Reputation: 23822
You can easily use the value that fgets
returns as a condition of your while
cycle:
while(fgets(buffer, sizeof(buffer), fp))
{
if(sscanf(buffer, "%14s%29s%f%f%f", name, surname, &mid1, &mid2, &final) == 5)
printf("%s %s %f %f %f\n",name,surname,mid1,mid2,final);
}
The cycle will stop when there are no more lines to read from the file.
Also, a good practice is to always check *scanf
return.
Limiting "%s"
specifiers size to their buffer is also recommended, this will avoid buffer overflow, in this case "%14s"
and "%29s"
for 15 char and 30 char buffer respectively, size - 1 relates to the need to reserve a space for the null terminator.
You should also follow the link in @pzaenger's comment regarding the use of while(feof(fp) == 0)
.
Upvotes: 2