Hey all. I'm very new to C++ and I've been following a series of tutorials and I decided to try and write a program similar to a text game. My basic outline was to get the user to supply their name and then chose one of three Pokemon (rather unoriginal I admit). Then rival would enter chose superior Pokemon and a small text battle would ensue where I could test my knowledge of the basic arithmetic operators based on the Pokemon's stats (Which I had declared as integers). However I encountered an unexpected problem before this when I tried to check whether the user had correctly typed either Bulbasaur, Charmander or Squirtle.
The code that I have written is:
1 2 3 4
if (pokemon != "Bulbasaur" || pokemon != "Charmander" || pokemon != "Squirtle"){
cout << "OAK: I'm sorry I don't understand...";}
elseif (pokemon == "Bulbasaur" || pokemon == "Charmander" || pokemon == "Squirtle"){
cout << "\nOAK " << name << ", You have chosen "<< pokemon << "! Great Choice!";}
I'm fairly sure name and pokemon have been declared correctly as strings so that's not the problem. Basically when I run this program it does not recognize when one of the three pokemon names have been typed correctly. I'm fairly sure it's to do with the line:
If you say if(x != 1 || x != 2), that means the if statement will always go through.
After all, if x is 1, then x != 2, therefore it's true. And if x is 2, then x != 1, so it's true.
If you want to exclude multiple possibilities, you'd want logical AND (&&), not OR (||)
1 2 3 4
if(pokemon != "Bulbasaur" && pokemon != "Charmander" && pokemon != "Squirtle")
{
// pokemon is something other than the above 3
}
Lastly, you don't need to be so redundant. If you're already checking all the conditions in your if statement, you don't need to repeat them for your else. It just makes the code more complicated and harder to maintain:
1 2 3 4 5 6 7 8
if(pokemon != "Bulbasaur" && pokemon != "Charmander" && pokemon != "Squirtle")
{
// pokemon is something other than the above 3
}
else // no need to put an 'if' here
{
// pokemon is one of the above 3
}
Thank you very much :) Originally I did have just the else without the second if but it wasn't working so I added a second If statement. And thanks I really should have thought more about that :/ I was thinking " if it's not a, b or c then do this" but i should've been thinking "if its not a, and it's also not b and it's also not c, then do this.
np. This is actually a surprisingly common problem. Along with things like if(a == 1 || 2 || 3). When it comes to the or operator, for whatever reason, people just want to literally translate english to C++. But it doesn't work that way.
If you have a similar problem in the future, just remember to step back, look at the code, and think of how the compiler is going to interpret it. Don't think about how it translates to English.