Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当scanf需要一个int值但被传递一个字符时,如何控制它的行为?_C_Function_Scanf - Fatal编程技术网

当scanf需要一个int值但被传递一个字符时,如何控制它的行为?

当scanf需要一个int值但被传递一个字符时,如何控制它的行为?,c,function,scanf,C,Function,Scanf,我正在做一个小程序(tic-tac-toe),我有一个基于玩家输入控制游戏模式的功能。现在让我们假设玩家插入一个角色,而不是三个合法值(0,1,2)。现在,如果玩家传递一个角色,默认值不会改变,因此while循环变为无穷大。 因此,我尝试创建一个值readedCharac,该值存储从scanf读取的字符数,但它没有解决问题。我错过了什么? 谢谢你的帮助 int playerChoice = -1; int readedCharac = 0; printf("\n\nWE

我正在做一个小程序(tic-tac-toe),我有一个基于玩家输入控制游戏模式的功能。现在让我们假设玩家插入一个角色,而不是三个合法值(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);
    }
intplayerchoice=-1;
int readedCharac=0;
printf(“\n\n欢迎参加TIC-TAC-TOE游戏\n\n”);
主菜单();
readedCharac=scanf(“%d”和playerChoice);
while((playerChoice<0 | | playerChoice>2)和&readedCharac==0)
{
printf(“\nInvelid条目重试\n”);
scanf(“%d”和playerChoice);
}

发生这种情况是因为scanf的缓冲区仍在寻找整数,所以它不可用。 您可以通过以下方式清空缓冲区:

fflush(stdin); 
这可能不适用于所有操作系统,接下来您可以使用下面的代码清空缓冲区:

while(getchar()!='\n'); 
因此:

intplayerchoice=-1;
int readedCharac=0;
printf(“\n\n欢迎参加TIC-TAC-TOE游戏\n\n”);
主菜单();
readedCharac=scanf(“%d”和playerChoice);
while((playerChoice<0 | | playerChoice>2)和&readedCharac==0)
{
而(getchar()!='\n');
printf(“\nInvelid条目重试\n”);
scanf(“%d”和playerChoice);
}

不要使用
scanf()
。使用
fgets()
阅读输入,然后在非常有用的地方解析:)
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); 
}