5
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

3 Answers 3

3

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') { ...
Sign up to request clarification or add additional context in comments.

Comments

1

I hope this will work for you. I have removed the \n inside the scanf and i have added while(getchar()!='\n'); for emptying stdin.

char player_select(void){

char player = 'n';

while(player == 'n'){
    printf("Select your player (X or O): ");
    scanf("%c", &player);

    if(player != 'X' && player != 'O'){
        printf("Invalid input. Try again.\n");
        player = 'n';
    }
    while(getchar()!='\n');
}

This is the output:

Select your player (X or O): A
Invalid input. Try again.
Select your player (X or O): X
Your character input is: X

1 Comment

Suggest while(getchar()!='\n'); outside the if() block to consume the \n if user enters a bad or good char.
0

Try:

    if (scanf("%c\n", &player) == 1 && player != 'X' && player != 'O'){
        printf("Invalid input. Try again.\n");
        player = 'n';
    }

Bring scanf into the if, removing from your above code, and check its return value == 1.

You can try removing the \n from scanf mask if this won't suffice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.