我正在做一个小程序(Tic tac toe),我有一个基于玩家输入来控制游戏模式的功能。现在假设玩家插入一个字符,而不是三个合法的值(0,1,2)。现在,如果玩家传递一个角色,默认值不会改变,因此while循环变成无限循环。所以我尝试创建一个值readedCharac
来存储从scanf读取的字符数,但是它没有解决这个问题。我遗漏了什么?感谢您的awnsers
int playerChoice = -1;
int readedCharac = 0;
printf("\n\nWELCOME TO TIC-TAC-TOE GAME\n\n");
mainMenu();
readedCharac = scanf("%d",&playerChoice);
while((playerChoice < 0 || playerChoice > 2) && readedCharac == 0 )
{
printf("\nInvelid Entry Retry \n");
scanf("%d",&playerChoice);
}
发布于 2020-04-11 19:21:11
这是因为scanf的缓冲区仍在查找整数,因此不可用。您可以通过以下方式清空缓冲区:
fflush(stdin);
这可能并不适用于所有操作系统,接下来您可以使用下面的代码清空缓冲区:
while(getchar()!='\n');
所以:
int playerChoice = -1;
int readedCharac = 0;
printf("\n\nWELCOME TO TIC-TAC-TOE GAME\n\n");
mainMenu();
readedCharac = scanf("%d",&playerChoice);
while((playerChoice < 0 || playerChoice > 2) && readedCharac == 0 )
{
while(getchar()!='\n');
printf("\nInvelid Entry Retry \n");
scanf("%d",&playerChoice);
}
https://stackoverflow.com/questions/61155763
复制相似问题