I'm trying to check against multiple possibilities in an if statement.
The user inputs a string, and then I check that string against multiple possibilities.
if (theString == "Seven" || "seven" || "7")
{
theInt = 7;
cout << "You chose: " << theInt << endl;
}
else if (theString == "Six" || "six" || "6")
{
theInt = 6;
cout << "You chose: " << theInt << endl;
}
So there's just a quick example of what I'm trying to accomplish. Any ideas?
I suppose that the type of the variable theString
is std::string
. Otherwise at least this comparison
theString == "Seven"
does not make sense,
The condition in the if statement
if (theString == "Seven" || "seven" || "7")
is equivalent to
if ( ( theString == "Seven" ) || ( "seven" ) || ( "7" ) )
and always yields true
because at least the address of the string literal "seven"
is not equal to zero. So this subexpression ( "seven" )
provides that the whole expression will be equal to true.
You should write
if (theString == "Seven" || theString == "seven" || theString == "7")
But it would be better at first to convert the string to upper or lower case.
For example
#include <algorithm>
#include <string>
#include <cstring>
//...
std::transform(theString.begin(), theString.end(), theString.begin(),
[](char c) { return std::toupper((unsigned char)c); });
if (theString == "SEVEN" || theString == "7")
{
theInt = 7;
cout << "You chose: " << theInt << endl;
}
else if ( theString == "SIX" || theString == "6" )
{
theInt = 6;
cout << "You chose: " << theInt << endl;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With