How to compare multiple strings inside an if statement?

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;
}

Leave a Comment