Reputation: 5
I'm doing a small progect(tic tac toe) and i have a function that controls game modes based on the input of the player. Now let's suppose the player inserts a character instead of the three legal values (0,1,2). Now if the player passes a character the default value isn't changed so the while loop becomes infinite.
So i have tried to create a value readedCharac
that stores the number of characters readed from scanf but it doesn't resolve the problem. What am I missing?
Thanks for your 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);
}
Upvotes: 0
Views: 37
Reputation: 535
This happens because buffer of scanf still looking for integer and so its not available . You can empty the buffer by :
fflush(stdin);
This might not work in all operating systems , next thing you can do is use code below to empty the buffer :
while(getchar()!='\n');
So:
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);
}
Upvotes: 1