Reputation: 3303
Ok, so I am having trouble reading in the string names and storing them in my struct array of type student. The age field is an int and the gpa field is a double and those worked fine. Then when I added the name to be read I started running into issues. How can I successfully read in a name and store it in the student.name field? The code below crashes and I am not sure why. I am new in C so please tell me if there is a better way to do this. Thank you in advance. Oh and the name is consecutive letters with no spaces between characters.
typedef struct student{
char *name; int age; double gpa;
}student;
void read(char *filename) {
File *file = fopen(filename,"r");
if(!file) return;
student *students = malloc(sizeof(student)*100);
int num_students = 10; //for example
int i;
for (i=0;i<num_students;i++) {
char *n = malloc(MAXLENGTH);
fscanf(file,"%s %i %lf", n,&students[i].age,&students[i].gpa); //<---runtime error occurs here
strcpy(students[i].name,n);
free(n);
}
/*code here to do stuff with the array*/
free(students);
fclosef(file);
}
Upvotes: 0
Views: 323
Reputation: 901
int n =0;
for (i=0;i<num_students;i++) {
char *n = malloc(MAXLENGTH);
n = fscanf(file,"%s %i %lf", n,&students[i].age,&students[i].gpa);
if(n!= 3 || n = EOF){
printf("invald input..");
}
students[i].name = malloc(strlen(n) +1);
if(student[i].name != NULL){
strcpy(students[i].name,n);
}
free(n);
}
man fscanf
Upon successful completion, these functions return the number of successfully matched
and assigned input items; this number can be 0 in the event of an early matching
failure. If the input ends before the first matching failure or conversion, EOF is
returned. If a read error occurs the error indicator for the stream is set, EOF is
returned, and errno is set to indicate the error.
Upvotes: 1
Reputation: 589
Your problem is that the "string" into the file that you want to store into n array does not have null terminator. So %s does not work fine into the fscanf(). Try another option to that, as treat it as a cvs file.
Upvotes: 0
Reputation: 2897
Try to replace this line strcpy(students[i].name,n);
with students[i].name = strdup(n);
I use strdup
to allocate enough memory to hold the string, if you tried =
it will work but will make name
as read only! strcpy()
will work too
Here you are reference for strdup use: strdup() - what does it do in C?
Also I don't see you allocating memory for students[i].name
Upvotes: 1