If/Else Help

I'm workking on making a Rock, Paper Scissors text-based game in C++, and I have an if Statement that just keeps giving back whatever the last value is.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    string pChoice;
    int ipChoice;




    cout << "Rock paper or scissors?\n" << endl;
    cin >> pChoice;

    if(pChoice == "rock" || "Rock"){
        ipChoice=1;

    }if(pChoice=="paper" || "Paper"){
        ipChoice=2;

    }if(pChoice=="scissors" || "Scissors"){
        ipChoice=3;

    }else{
        cout << "I'm sorry, I didn't understand\n" << endl;
        }
    cout << ipChoice;


It will ALWAYS output the third if block, no matter what the user inputs.
First, why do you have \n and endl in the same thing. Do you really need both new lines?

But I would suggest you declare your string like this: string pChoice ="";. Also, maybe declare a char called ch up there, and then write:
1
2
3
4
5
6
7
cout<<"Rock, paper or scissors?"<<endl;
ch=getch();
while(ch!=13){
pChoice.push_back(ch);
ch=getch();
}
/*and then your if statements*/

Just remember to #include <conio.h> .
I use \n alot because I'm used to python,

And what does this:
1
2
3
4
5
ch=getch();
while(ch!=13){
pChoice.push_back(ch);
ch=getch();
}

Actually do? It gets the user's answer, but why do I need a the while loop?
And what does pChoice.push_back(ch); do? I'm new to C++ and I want to be helped so I can prevent things like this. Not given the answer
Last edited on
First, all the conditional statements will all return true because only one side of the OR must be true. The constant / literal ("Rock", "Paper", "Scissors") on the right side of the OR will always be true, therefore the entire statement will evaluate to true.

Second, you are not using 'else if' statements so the first 'if' evaluates to true and ipChoice = 1, then the second 'if' statement evaluates to true and ipChoice = 2, and the same for the third 'if' statement when ipChoice = 3. The final 'else' is not entered. In the end ipChoice will always = 3.

Try this:

1
2
3
4
5
6
7
8
9
10
11
12
cout << "Rock paper or scissors?\n" << endl;
cin >> pChoice;

if(pChoice == "rock" || pChoice == "Rock") {
	ipChoice = 1;
} else if(pChoice == "paper" || pChoice == "Paper") {
	ipChoice = 2;
} else if(pChoice == "scissors" || pChoice == "Scissors") {
	ipChoice = 3;
} else {
	cout << "I'm sorry, I didn't understand\n\n";
}


Another suggestion is to convert the input to all lower case before testing it which will simplify the conditionals.
Last edited on
Topic archived. No new replies allowed.