我正在编写一个模拟Monty Hall 问题的命令行 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 语句没有任何关系。