Elizabeth Ekefre
Elizabeth Ekefre

Reputation: 7

Getting looped struct data into a file in C

I have a looped struct array that accepts student name and roll number for as many students the user inputs

Code:

int x;
struct studs
{
    char name[50];
    char rollno[50];
}student[50];

            printf("\t\t________________________________");
            printf("\n\n\t\t\tStudent Registration");
            printf("\n\t\t_______________________________");
            printf("\n\n\tHow many students in %s ", course);
            scanf("%d", &stud);

            admin = fopen(name, "a");
            fprintf(admin, "\nNumber of students for %s: %d", course, stud);
            fclose(admin);

            for(x=0; x<stud; x++)
            {
                printf("\n\nStudent %d", x+1);
                printf("\n_____________________________");
                printf("\n\nStudent Name : ");
                scanf("%s", student[x].name);
                printf("\nStudent Rollno. : ");
                scanf("%s", student[x].rollno);
                system("\npause");
                goto exam;
            }
            admin = fopen("student.txt", "w");
            fprintf(admin, "Name: %s \nRoll Number: %s\n\n", student.name, student.rollno);
            fclose(admin);

As you can see i'm trying to put each name and number into the text file but I keep getting this errors

error: request for member 'name' in something not a structure or union | error: request for member 'rollno' in something not a structure or union

Is there anyway to get this into a file, with or without the struct?

Upvotes: 0

Views: 56

Answers (1)

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

This

fprintf(admin, "Name: %s \nRoll Number: %s\n\n", student.name, student.rollno);

cannot work, student is an array of stud's (or at least it would be if i were in the school). You have already shown that you know how to iterate over the number of students with for(x=0; x<stud; x++), so just do it again:

for(x=0; x<stud; x++) {
    fprintf(admin, "Name: %s \nRoll Number: %s\n\n", student[x].name, student[x].rollno);
}

There are likely going to be other errors in your program (Like that goto exam immediately jumping out of your for loop to somewhere). But this will at least deal with the error you have described.

Upvotes: 1

Related Questions