Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't my for-loop printing in the second loop?

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.

like image 752
Belal Kassem Avatar asked Jan 23 '26 20:01

Belal Kassem


1 Answers

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.

like image 68
CFLS Avatar answered Jan 25 '26 11:01

CFLS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!