Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

C++ multiple strings inside an if statement

I'm having an issue 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. In my program, these if statements are in a function, and I am using #include [string]. (I'm not even sure if "6" or "7" is possible, but I can't even test my code right now :( So right now in my code, if the user input 6, my program would run and assign a value of 7 to theInt. Any ideas?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...