Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanning character in a while loop

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

like image 456
Brandacus Avatar asked Oct 02 '22 11:10

Brandacus


1 Answers

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') { ...
like image 177
chux - Reinstate Monica Avatar answered Oct 13 '22 09:10

chux - Reinstate Monica