Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ multiple strings inside an if statement

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?

like image 296
Jveto Avatar asked Apr 19 '17 01:04

Jveto


1 Answers

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;
}
like image 83
Vlad from Moscow Avatar answered Sep 23 '22 06:09

Vlad from Moscow