I am writing a command line C program that simulates the Monty Hall Problem, but I am having trouble with a particular section of my code, where the program simply prompts the user to input the number door they would like to open, it gets the input and makes sure it is valid:
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);
The program works fine until you input any of the valid door numbers: 1, 2 or 3, it doesn’t crash but doesn’t print the desired output after the while loop and continue with the program. However, the name of the door chosen is printed when I input a valid number, which suggests that it isn’t anything to do with the switch statement.
You’re shadowing
valid_inputfrom within thewhileloop scope:When you write to or read from
valid_inputin the loop, you are reading from the one declared in the loop, not outside of it. So, thevalid_inputyour loop checks for actually never changes.