나는 Monty Hall Problem을 시뮬레이트하는 명령 행 C 프로그램을 작성하고 있지만, 프로그램이 단순히 열 수있는 숫자 문을 입력하라는 메시지를 표시하는 코드의 특정 부분에 문제가있다. 입력을 얻는다. 그것은 유효 확실하게 :이 C 프로그램이 while 루프 후에 작동하지 않는 이유는 무엇입니까?
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, 그것은 충돌하지 않습니다하지만 잠시 후 원하는 출력을 인쇄하지 않습니다 반복하고 프로그램을 계속 진행하십시오. 그러나 유효한 문구를 입력 할 때 선택된 문의 이름이 인쇄됩니다.이 문구는 switch 문과 관련이 없음을 나타냅니다.
정수를 직접 입력 한 다음 유효성 검사를 수행하는 것이 왜 1,2 또는 3이 아닌지 사용자가 다시 입력하게하지 마십시오. – Rndm
사용자가 정수가 아닌 다른 값을 입력하면 충돌을 일으키지 않도록 프로그램을 바보로 만들려고합니다. – Harry