[英]I'm trying to identify the number of student entered in do-while , and display the number out-side the loop
[英]How do I break out of a loop while creating a string array when the max number of strings allowed is entered?
我正在尝试打印用户输入的朋友姓名列表。 可以输入的最大名称数为 5。用户还可以选择输入 < 5。我不明白为什么在输入 5 个名称时我无法跳出循环? 谢谢
#include <stdio.h>
int main(void) {
char namesArray[5][100]; //5 = number of names while 100 = the maximum length of the name
int x, y;
char yesNo;
int counter = 0;
do {
for (x = 0; x < 5; x++) {
printf("\nEnter a friends name: ");
scanf(" %s", &namesArray[x][0]);
counter++;
printf("\nWould you like to enter another friends name? Y or N: ");
scanf(" %c", &yesNo);
if (yesNo == 'N')
break;
}
} while (yesNo == 'Y' || counter == 5);
if (yesNo == 'N' || counter == 5){
for (x = 0; x < counter; x++) {
printf("\n\n%s", namesArray[x]);
}
}
return 0;
}
回答你的问题:
您的 do-while 循环永远不会结束,因为达到条件时counter
永远不会为5
。 您在 for 循环内增加counter
,当x
为5
时结束。 因此,当您离开第一个 for 循环时, counter
将为6
。 (因为当循环开始时x
是0
并且您将counter
增加到1
)
因此,使您的代码工作的更改是将 do-while 条件更改为:
while (yesNo == 'Y' || counter < 5);
更好的解决方案是稍微更改代码以完全摆脱 do-while 循环。 您可以只使用 for 循环(以确保最多输入 5 个名称)并向其中添加yesNo
的条件,以便您可以在输入 5 个名称之前突破。
所有其他评论都是真实的,所以你可能想要这样的东西:
#include <stdio.h>
int main(void)
{
char namesArray[5][100]; // 5 = number of names, 100 = max length of each
char yesNo;
int counter;
for (counter = 0; counter < 5; counter++) {
printf("\nEnter a friends name: ");
scanf(" %99s",namesArray[counter]);
printf("\nWould you like to enter another friends name? Y or N? ");
scanf(" %c", &yesNo);
if (yesNo == 'N')
break;
}
for (int x = 0; x < counter; x++)
printf("\n\n%s",namesArray[x]);
exit(0);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.