Please consider the following code:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main(int argc, char** argv) {
enum object {rock, paper, scissors};
object player1, player2;
cout << " "Enter "r" for rock, "p" for paper or "s" for scissors:";
char p1, p2;
cin >> p1 >> p2;
if (p1 == 'r') {player1 = rock;}
else if (p1 == 'p') {player1 = paper;}
else if (p1 == 's') {player1 = scissors;}
else {cout << "invalid input, play again" << endl; exit(1);}
if (p2 == 'r') {player2 = rock;}
else if (p2 == 'p') {player2 = paper;}
else if (p2 == 's') {player2 = scissors;}
else {cout << "invalid input, play again" << endl; exit(1);}
if (player1==player2) cout <<"objects are equal";
else if (player1==rock && player2==paper) cout << "player 2 is the winner";
else if (player1==rock && player2==scissors) cout<<"player 1 is the winner";
else if (player1==paper && player2==rock) cout << "player 1 is the winner";
else if (player1==paper && player2==scissors) cout <<"Palyer 2 is the winnder";
else if (player1==scissors && player2==paper) cout << "Player 1 is winner";
else cout <<"Player 2 is the winner";
cout << endl;
}
How can the above code be rewritten with the switch statement while the user has to give the full word (rock, paper, scissors) instead of the initials for the input.
Update: I have converted part of the code with switch, but I was interested to see if I could use it for the entire code:
For instance:
switch (p1) {
case 'r': player1=rock; break;
case 'p': player1=paper; break;
case 's': player1=scissors; break;
}
instead of
if (p1 == 'r') {player1 = rock;}
else if (p1 == 'p') {player1 = paper;}
else if (p1 == 's') {player1 = scissors;}
else {cout << "invalid input, play again" << endl; exit(1);}