When I take user’s name as input and use that information to do another task, the output does not contains first character of the first student name.
int main() {
// Task1 - Enter student number
int i, number;
printf("Enter the number of students: ");
scanf("%d", &number);
getchar();
while (number > 1000) {
printf("Your number is too high. Maximum number of student is 1000. Please enter again: ");
scanf("%d", &number);
}
//Task2 - get student info
struct studentInfo students[number];
for (i = 0; i < number; i++) {
printf("\nEnter data for student %d:\n", i + 1);
printf("Enter student %d name: ", i + 1);
getchar(); // consume the newline character left in the input stream
fgets(students[i].fullName, sizeof(students[i].fullName), stdin); //use fgets instead of scanf
students[i].fullName[strcspn(students[i].fullName, "\n")] = 0; // Remove trailing newline
printf("Enter student %d ID: ", i + 1);
scanf("%s", students[i].ID);
printf("Enter student %d birthdate: ", i + 1);
scanf("%s", students[i].birthDate);
}
}
I have changed fgets to gets and add getchar but it’s still not working
The problem is after
scanf("%d", ...), a newline is left in the input stream. Use ofscanf()for keyboard input is a bad idea. Consider usingfgets()andsscanf()instead.Example:
would become:
Where you declare
keyboard_lineaschar keyboard_line[80];at the top ofmain();