scanf需要int值但传递字符时如何控制其行为?

问题描述 投票:0回答:1

我正在做一个小的项目(井字游戏),并且我有一个功能可以根据玩家的输入来控制游戏模式。现在,假设玩家插入一个字符而不是三个合法值(0,1,2)。现在,如果玩家传递角色,则默认值不会更改,因此while循环变为无限。因此,我试图创建一个值readedCharac,该值存储从scanf读取的字符数,但无法解决问题。我想念什么?感谢您的遮阳篷

    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);
    }
c function scanf
1个回答
0
投票

这是因为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); 
}
© www.soinside.com 2019 - 2024. All rights reserved.