The following code is supposed to prompt the user for the number of students and number of assignments and then prompt them to enter the name of each student.
When it reaches the loop to ask for student names for some reason it prints the prompt twice on one line
Student name: Student name:
Could someone please tell me why this happens? And how to fix it?
I have run into this issue several times but in different scenarios.
#include <stdio.h>
#include <cstring>
void print_array(char str[20][20], int number) {
int i;
for (i=0; i < number; i++) {
printf("%s\n", str[i]);
}
printf("---\n");
}
void main() {
int students, assignments;
char names[20][20];
do {
printf("How many students are there (between 1 and 20)?");
scanf("%d", &students);
if (students < 1 || students > 20)
printf ("Number of students must be between 1 and 20.\n");
} while (students < 1 || students > 20);
do {
printf("How many assignments are there (between 1 and 10)?");
scanf("%d", &assignments);
if (assignments < 1 || assignments > 10)
printf ("Number of assignments must be between 1 and 10.\n");
} while (assignments < 1 || assignments > 10);
int i;
for(i=0; i < students; i++){
printf("Student name:");
fgets(names[i], 20, stdin);
}
print_array(names, students);
}