Do-while and if else problem

This program compiles fine and runs alright once through but i think the loop is messed up but I can't seem to find out why. can someone please help me?


#include <iostream>
using namespace std;

int main()
{
char player1;
char player2;
char answer;

cout << "Enter R for rock, P for paper, or S for scissors and press enter\n";
cin >> player1;
cout << "Enter R for rock, P for paper, or S for scissors and press enter\n";
cin >> player2;

do
{
if (player1 == player2)
cout << "It's a tie!";
else
{
if (player1 == 'p' || 'P' && player2 == 's' || 'S')
cout << "Player 2 wins because scissors beats paper!";
else if (player1 == 'p' || 'P' && player2 == 'r' || 'R')
cout << "Player 1 wins because paper beats rock!";
else if (player1 == 's' || 'S' && player2 == 'r' || 'R')
cout << "Player 2 wins because rock beats scissors!";
else if (player1 == 's' || 'S' && player2 == 'p' || 'P')
cout << "Player 1 wins because scissors beats paper!";
else if (player1 == 'r' || 'R' && player2 == 'p' || 'P')
cout << "player 2 wins because paper beats rock!";
else if (player1 == 'r' || 'R' && player2 == 's' || 'S')
cout << "Player 1 wins because rock beats scissors!";
else if (player1 != 'p' || 'P' || 'r' || 'R' || 's' || 'S')
cout << "error, player 1, you must enter either R, P, or S";
else if (player2 != 'p' || 'P' || 'r' || 'R' || 's' || 'S')
cout << "error, player 2, you must enter either R, P, or S";
}
cout << "Do you want to play again? Enter y or n and press enter";
cin >> answer;
} while (answer == 'y' || 'Y');
cout << "Game over.";

}
Your code:
if (player1 == 'p' || 'P' && player2 == 's' || 'S')
is basically the same as
1
2
3
if ( (player1 == 'p') ||
     ( ('P' != 0) && (player2 == 's') ) ||
     ('S' != 0) )

I'm pretty sure that's not what you want.

You'd need to write it as
1
2
if ( (player1 == 'p' || player1 == 'P') &&
     (player2 == 's' || player2 == 'S')

or even better, #include <cctype> and then you can just do
if (tolower(player1) == 'p' && tolower(player2 == 's')).
thank you! do you know what is wrong with the loop by chance? because it outputs a winner and will prompt you asking to play again but it won't let you play again?
That's because the part where you actually enter your choice:
1
2
3
4
cout << "Enter R for rock, P for paper, or S for scissors and press enter\n";
cin >> player1;
cout << "Enter R for rock, P for paper, or S for scissors and press enter\n";
cin >> player2;

is outside of the loop, so it'll only ever run once.
thank you! I put it within the "do" and it worked perfectly! do you know how to make the game keep score?
Topic archived. No new replies allowed.