With this text file:
Code:
Name: Able Anderson
Major: BIO
GPA: 3.4
Name: John Smith
Major: EE
GPA: 3.85
Name: Charles Green
Major: CS
GPA: 2.75
I'd suggest:
Code:
#include <stdio.h>
#include <string.h>
int main(void) {
int i;
char names[3][40], major[3][30];
char colon[3]={6,7,5}; //offset to the colon in the string of text+2
char buffer[40];
float gpa[3];
FILE *fp=fopen("test.txt","r");
if(!fp) {
printf("Error! File did not open.\n");
return 1;
}
i=0;
while(fgets(buffer, sizeof(buffer), fp)!=NULL) {
//printf("buffer:%s\n",buffer);
sscanf(buffer+colon[0], "%[^\n]",names[i]);
//get major
fgets(buffer, sizeof(buffer), fp);
sscanf(buffer+colon[1], "%[^\n]",major[i]);
//get gpa
fgets(buffer, sizeof(buffer), fp);
sscanf(buffer+colon[2], "%f",&gpa[i]);
printf("%s\n%s\n%.2f\n\n",names[i],major[i],gpa[i]);
++i;
}
fclose(fp);
printf("\n");
return 0;
}
I tried a few other ideas, but they either were more of an intermediate type, or they were too complex or long.