char player_select(void){
char player = 'n';
while(player == 'n'){
printf("Select your player (X or O): ");
scanf("%c\n", &player);
if(player != 'X' && player != 'O'){
printf("Invalid input. Try again.\n");
player = 'n';
}
}
printf("Your character input is: %c\n", player);
exit(0);
return player;
}
I am getting some weird output here:
Select your player (X or O): X
Invalid input. Try again.
Select your player (X or O): i
Your character input is: X
Incorrect use of scanf()
// scanf("%c\n", &player);
scanf(" %c", &player);
The '\n'
in "%c\n"
does not do what you think. '\n'
tells scanf()
to consume white-space like '\n'
and ' '
until non-white-space occurs. You input was not as described.
Since stdin
is buffered, text by itself, will not typically get read until a '\n'
follows.
It gets complicated to explain in detail why things failed. So briefly, use " %c"
instead of "%c\n"
. Or better yet, use fgets()
.
buffer player[10];
fgets(ch, sizeof ch, stdin);
if(player[0] != 'X' && player[0] != 'O') { ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With