gpt4 book ai didi

c - 为什么这个 C 程序在 while 循环后不工作?

转载 作者:太空宇宙 更新时间:2023-11-04 06:38:47 25 4
gpt4 key购买 nike

我正在编写模拟 Monty Hall Problem 的命令行 C 程序,但我在代码的特定部分遇到了问题,程序只是提示用户输入他们想要打开的数字门,它获取输入并确保它是有效的:

printf("Please enter the door you would like to choose! (Door 1, 2 or 3)\n\nDoor ");

char init_input[255];

int selection;
int valid_input = 0;
while(valid_input == 0)
{
gets(init_input);
int len = strlen(init_input);
while(len != 1)
{
printf("Please choose either door 1, 2 or 3\n\n");
printf("Door ");
gets(init_input);
len = strlen(init_input);
}
int valid_input = 0;
char input = init_input[0];
switch(input)
{
case('1'):
{
selection = 1;
valid_input = 1;
printf("Door 1\n");
break;
}
case('2'):
{
selection = 2;
valid_input = 1;
printf("Door 2\n");
break;

}
case('3'):
{
selection = 3;
valid_input = 1;
printf("Door 3\n");
break;


}
default:
{
printf("\nPlease choose either door 1, 2 or 3\n\nDoor ");
break;
}
}
}

printf("\nYou chose Door %d, now I will reveal one of the doors that has a goat behind it:\n\n", selection);

程序运行正常,直到您输入任何有效的门号:1、2 或 3,它不会崩溃,但不会在 while 循环后打印所需的输出并继续执行程序。然而,当我输入一个有效数字时,选择的门的名称被打印出来,这表明它与 switch 语句没有任何关系。

最佳答案

您正在从 while 循环范围内隐藏 valid_input:

int valid_input = 0;
while (valid_input == 0) {
// ...
int valid_input = 0; // remove this
}

当您在循环中写入或读取 valid_input 时,您是从循环中声明的那个读取,而不是在循环之外。因此,您的循环检查的 valid_input 实际上永远不会改变。

关于c - 为什么这个 C 程序在 while 循环后不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11481564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com