Reputation: 63
I want to get student name mid-term and final points and write them in a txt file but when I use a loop, It never get student name. It always gives it a miss. How can I use feof with a loop? I want to get student names mid-term and final point and calculate the average from the got points and It must get always name and points till user press the end of file.
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
FILE *Points;
char namesOfStudents[10];
int pointsOfStudents[1][2];
double AverageOfStudents[1];
int i=0,j=1;
int numberOfStudents;
Points = fopen("C:\\Users\\Toshiba\\Desktop\\PointsOfStudent.txt", "a+");
fprintf(Points, "Name\t\t 1.Grade\t2.Grade\t\tAverage\n");
/* printf("How many students will you enter: ");
scanf("%d",&numberOfStudents);*/
//while (!feof(Points))
printf("Please enter new students name: ");
gets(namesOfStudents);
printf("\nPlease enter new students first point: ");
scanf("%d",&pointsOfStudents[0][0]);
printf("\nPlease enter new students second point: ");
scanf("%d",&pointsOfStudents[0][1]);
for (; i < strlen(namesOfStudents); i++)
{
fprintf(Points, "%c", namesOfStudents[i]); //To write
student name to file
}
fprintf(Points,"\t\t ");
fprintf(Points,"%d\t\t",pointsOfStudents[0][0]); //to write
student's first point
fprintf(Points,"%d\t\t",pointsOfStudents[0][1]); //to write
student's second point
fprintf(Points,"%d\n",(pointsOfStudents[0][0]+pointsOfStudents[0]
[1])/2); //to calculate and write average
system("cls");
fclose(Points);
system("Pause");
}
Upvotes: 1
Views: 1548
Reputation: 123596
Several things:
First, NEVER NEVER NEVER NEVER NEVER use gets
- it is dangerous, it will introduce a point of failure and/or massive security hole in your code, and it has been removed from the standard library as of the 2011 version of the language standard. Use fgets
instead:
fgets( nameOfStudents, sizeof nameOfStudents, stdin );
Secondly, while( !feof( fp ) )
is always wrong. On input from fp
, it will loop one time too often. On output to fp
, it is meaningless.
You can use the result of fgets
to control your loop:
while ( fgets( nameOfStudents, sizeof nameOfStudents, stdin ) )
{
...
}
When you're done entering data from the terminal, signal an EOF using either CtrlZ or CtrlD (depends on your platform).
Third, main
returns int
, not void
; use
int main( void )
instead.
Finally, change
for (; i < strlen(namesOfStudents); i++)
{
fprintf(Points, "%c", namesOfStudents[i]); //To write student name to file
}
to
fprintf( Points, "%s", nameOfStudents );
to write the student name to the file.
There are other problems, but make those changes and see if that doesn't help.
Upvotes: 3