Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

c - Why when i put the right input the switch statement get ignored

OUTPUT:

Select your sign Tom:        [X]    or    [O]
Y
ERROR ENTER A DIFFERENT CHARACTER
X
Player 2 = O    

But i want it like that:

Select your sign Tom:        [X]    or    [O]
Y
ERROR ENTER A DIFFERENT CHARACTER
X
Player 1 = X
Player 2 = O 
printf("Select your sign %s:        [X]    or    [O]
", PLAYER1);
        scanf(" %c", &P1_SIGN);

            do{
                switch (P1_SIGN) {          //entrata segni

                case 'X':
                    puts("Player 1 = X
");
                    P1_SIGN = 'X';
                    break;

                case 'x':
                    puts("Player 1 = X
");
                    P1_SIGN = 'X';
                    break;

                case 'O':
                    puts("Player 1 = O
");
                    P1_SIGN = 'O';
                    break;

                case 'o':
                    puts("Player 1 = O
");
                    P1_SIGN = 'O';
                    break;
                
                default:
                    puts("ERROR ENTER A DIFFERENT CHARACTER");
                    scanf(" %c", &P1_SIGN);
                    break;
                    
            }} while(P1_SIGN != 'X' && P1_SIGN != 'x' && P1_SIGN != 'O' && P1_SIGN != 'o');

            if (P1_SIGN == 'X' || P1_SIGN == 'x') {

                puts("Player 2 = O
");
            } else {

                puts("Player 2 = X
");
            }          

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have your scanf()s in wrong positions.

The second scanf() will read the input X and it will make the condition of do-while loop false. Therefore, the loop body won't run again and therefore Player 1 = X isn't printed.

You should remove both of your scanf()s and instead of them add one scanf() inside the do-while loop, before the switch statement.


            do{
                scanf(" %c", &P1_SIGN); // put scanf() here
                switch (P1_SIGN) {          //entrata segni

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...