在文字输入在第一scanf()
,第二个不运行。 getchar()
无法再次尝试输入。它跳过去输入你想再玩一次吗? (Y/N)?似乎your_choice
应该采取的性格和事后检查,但性格实际上正在采取ch
。是什么导致它像这样工作以及如何解决问题。我试过重新初始化变量,但不起作用。SCANF不工作无效的输入
#include <stdio.h>
void choice(int);
int main() {
char ch;
int random, your_choice;
do {
srand(time(NULL));
system("cls");
printf("** 0 is for Rock **\n");
printf("** 1 is for Scissors **\n");
printf("** 2 is for Lizard **\n");
printf("** 3 is for Paper **\n");
printf("** 4 is for Spock **\n");
printf("\nEnter your choice here:");
scanf("%d", &your_choice);
random = rand() % 5; //random number between 0 & 4
if ((your_choice >= 0) && (your_choice <= 4)) {
//choice printer omitted for this post
if ((random == ((your_choice + 1) % 5)) || (random == ((your_choice + 2) % 5)))
printf("\n\n... and you win!!!\n");
else if ((random == ((your_choice + 3) % 5)) || (random == ((your_choice + 4) % 5)))
printf("\n\n... and you lose!!!\n");
else if (random == your_choice)
printf("\n\nUnfortunately, it's a tie!\n");
} else
printf("\nWell, this is wrong! Try again with a number from 0 to 4!!\n");
printf("\nWould you like to play again? (Y/N)?: ");
scanf(" %c", &ch);
} while (ch == 'y' || ch == 'Y');
return 0;
}
对于初学者,带走你的空间在第二'scanf' – jiveturkey
了'%C'前检查scanf'的'的返回值。如果存在解析错误,则无效输入保留在输入缓冲区中,因此在尝试再次扫描相同数据之前,必须先将其清除。如果忽略'scanf'的返回值并且不对其解析错误做出反应,那么通常会导致程序在无效输入上表现完全出乎意料。 – hyde
@hyde打印时,它给出了选择输入的值。 – nAiN