Reputation: 77
I made a for loop that stores names in a array that the user selects it's size however when the for-loop runs it skips the second printf
statement.
int NumToDelete;
printf("How much employees do you want to remove?\n");
scanf(" %d", &NumToDelete);
char Name[NumToDelete][25];
for(int i = 0; i < NumToDelete; i++)
{
fgetc(stdin); //To stop the program from doing
printf("Name: "); //something like this: Name:Name:
fgets(Name[i], 25, stdin);
}
The prompts and user input should look something like this (if NumToDelete
is 3):
Name: Ahmed
Name: John
Name: Bob
But instead, after I enter the name "Ahmed", I have to enter the second name "John" before the code displays the "Name:" prompt again. So the text in the console ends up looking like this:
Name: Ahmed
John
Name: Bob
The names being the user input. Thank you in advance.
Upvotes: 3
Views: 96
Reputation: 355
I think that fgetc should be outside of the for-loop. Try this code:
int NumToDelete;
printf("How much employees do you want to remove?\n");
scanf(" %d", &NumToDelete);
fgetc(stdin);
char Name[NumToDelete][25];
for(int i = 0; i < NumToDelete; i++)
{
printf("Name: ");
fgets(Name[i], 25, stdin);
}
The reason for this is that fgets
consumes the trailing newline from its input, but not the leading newline.
Upvotes: 6