[英]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. 我创建了一个for循环,用于将名称存储在用户选择其大小的数组中,但是当for循环运行时,它会跳过第二个printf
语句。
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): 提示和用户输入应如下所示(如果NumToDelete
为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. 但是,在我输入名称“Ahmed”之后,我必须在代码再次显示“Name:”提示之前输入第二个名称“John”。 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. 先感谢您。
I think that fgetc should be outside of the for-loop. 我认为fgetc应该在for循环之外。 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. 原因是fgets
从其输入中消耗了尾随换行符,但不是前导换行符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.