Keep asking the user to input the the character until it is not either A, B or C two times

Viewed 42

I have written a program that asks a user to input a character A, B or C. If the user enters another character, it outputs the message and asks the user to input character again. User enters the character two times. It outputs the message two times. How can I fix this problem?

char player1, player2;

do
{
    printf("Enter Player 1 choice ('A','B','C') \n");

    scanf("%c", &player1);

    if(player1 != 'A' && player1 != 'B' && player1 != 'C')
    {
        printf("Invalid input! \n");
    }
   
} while (player1 != 'A' && player1 != 'B' && player1 != 'C');


do
{
    printf("Enter Player 2 choice ('A','B','C') \n");

    scanf("%c", &player2);

    if(player2 != 'A' && player2 != 'B' && player2 != 'C'){

        printf("Invalid input! \n");
    }
    
} while (player2 != 'A' && player2 != 'B' && player2 != 'C');


return 0;
1 Answers

this is due to the buffer, when the user enters 1 char like A for example then presses enter, what is stored in the buffer is A\n, which are 2 characters. if the user enters 2 chars like A then K then press enter, what is stored in the buffer is AK\n, when you use scanf, it will read only the first char which is A then it will leave the other characters in the buffer. then you have to flush your buffer, you can use fflush(stdin); to do that but it's UB (undefined behavior and not portable) for most compilers, the other way to do that is to use the fgets method with a dummy char array, so instead of writing :

scanf("%c", &player1);

you can write

scanf("%c", &player1);

fgets(dummyBuffer, sizeof(dummyBuffer), stdin);

where dummyBuffer is a dummy char buffer defined at the beginning. and you can use it to clear your buffer.

and here is the full code with this only small modification:

#include <stdio.h>

int main(void){
    char player1, player2;
    char dummyBuffer[20];

    do
    {
        printf("Enter Player 1 choice ('A','B','C') \n");

        scanf("%c", &player1);

        fgets(dummyBuffer, sizeof(dummyBuffer), stdin);

        if(player1 != 'A' && player1 != 'B' && player1 != 'C')
        {
            printf("Invalid input! \n");
        }

    } while (player1 != 'A' && player1 != 'B' && player1 != 'C');


    do
    {
        printf("Enter Player 2 choice ('A','B','C') \n");

        scanf("%c", &player2);

        fgets(dummyBuffer, sizeof(dummyBuffer), stdin);

        if(player2 != 'A' && player2 != 'B' && player2 != 'C'){

            printf("Invalid input! \n");
        }

    } while (player2 != 'A' && player2 != 'B' && player2 != 'C');


    return 0;
}

and this is the output:

Enter Player 1 choice ('A','B','C')
D
Invalid input!
Enter Player 1 choice ('A','B','C')
A
Enter Player 2 choice ('A','B','C')
K
Invalid input!
Enter Player 2 choice ('A','B','C')
B
Related