I just started learning C and have this code which asks for a name, student number, and grades. The data is stored in an array of structures. It's supposed to loop 3 times (size of structure array) it works fine at the first iteration. I have a problem on the succeeding iterations as the input field for the name is getting skipped, and it goes straight through asking for the student number. It should not skip asking for the name part but it does as a result, the fields for the name for the second and third class numbers are empty. Why is this happening and how can I fix this?
#include <stdio.h>
#include <string.h>
struct student {
char nameLF[50];
int student_number;
float gwa;
};
void attendance(struct student *A, int class_number) {
int length;
printf("Enter Your Name: ");
fgets(A[class_number].nameLF, 50, stdin);
length = strlen(A[class_number].nameLF);
A[class_number].nameLF[length] = '\0';
printf("\nHello %s!\n", A[class_number].nameLF);
printf("Enter your Student Number: ");
scanf("%d", &A[class_number].student_number);
printf("Enter your GWA: ");
scanf("%f", &A[class_number].gwa);
printf("Attendance success!\n");
}
void printAttendance(struct student *A, int class_number) {
printf("Name: %s\n", A[class_number].nameLF);
printf("Class Number: %d\n", A[class_number].student_number);
printf("GWA: %f\n", A[class_number].gwa);
}
int main() {
struct student SectionOne[3];
int classNumber, length;
classNumber = 0;
while (classNumber < 3) {
attendance(SectionOne, classNumber);
classNumber++;
printf("--- Class number: %d\n", classNumber);
}
printf("===== Class List =====\n");
for (classNumber = 0; classNumber < 3; classNumber++) {
printAttendance(SectionOne, classNumber);
printf("\n");
}
printf("Complete Attendance!");
return(0);
}
Output Part 1: Asking for info Output Part 2: Printing gathered info