Wazzup!
Say I have a file of names and quiz scores of format:
<Name> <ID #> <Q1> <Q2> <Q3> <Q4> <Exam>
how could I read from this file into a structure if for each student, the 4 quiz scores and exam score are to be stored in one array?
Thanks
A
Wazzup!
Say I have a file of names and quiz scores of format:
<Name> <ID #> <Q1> <Q2> <Q3> <Q4> <Exam>
how could I read from this file into a structure if for each student, the 4 quiz scores and exam score are to be stored in one array?
Thanks
A
You can get the input from the file using fgets and then parse the line. You could parse the line with fscanf or capture each number up to a space.
- Sean
If cities were built like software is built, the first woodpecker to come along would level civilization.
Black Frog Studios
This should work. But some error checking wouldnt harm.Code:#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define NUMBER_OF_STUDENTS 25 typedef struct { char name[30]; int id; int score[5]; } STUDENT; int main (void) { STUDENT student[NUMBER_OF_STUDENTS]; int i = 0, student_counter = 0; char c, buff[1024], *locator; FILE *fp; memset (student, 0, sizeof student); if (!(fp = fopen ("datafile", "r"))) perror ("Unable to open file"), exit (EXIT_FAILURE); while (fgets (buff, 1024, fp)) { while (isalpha (c = *(buff + i)) || c == ' ') student[student_counter].name[i] = c, i++; student[student_counter].id = strtol (buff + i, &locator, 0); i = 0; while (*locator) { if (*locator == ' ') locator += 1; else { student[student_counter].score[i] = strtol (locator, NULL, 0); locator += strcspn (locator, " "); i++; } } student_counter++, i = 0; } fclose (fp); return 0; }
Hey Char,
thanks for the code..are you sure it works? Also, how could i simplify it a bit so as to make it my level??
Thanks though
A