I have a problem with the following code:
int main(){
string name;
cout<<"Enter: ";
cin>>name;
if(name == "AHAH"||"AHAH"||"ADAD"||"ACAC"||"ASAS"||"AHAD"||"AHAC"||"AHAS"||"ADAH"||"ADAC"\
||"ADAS"||"ACAH"||"ACAD"||"ACAS"||"ASAH"||"ASAD"||"ASAC"){
cout<<"Call! Good hand!";
}
else if(name == "2H2H")
cout<<"Rase";
system("pause");
};
No matter what I input the program outputs:
Call! Good hand!
What's the problem?
答案 0 :(得分:4)
When you have so many variants to compare with it could be better to keep them in container and then use algorithm or loop to compare:
std::set<std::string> names { "AHAH", "AHAH", "ADAD", "ACAC",
"ASAS", "AHAD", "AHAC", "AHAS",
"ADAH", "ADAC" };
if( names.count( name ) )
cout<<"Call! Good hand!";
or vector:
std::vector<std::string> names { "AHAH", "AHAH", "ADAD", "ACAC",
"ASAS", "AHAD", "AHAC", "AHAS",
"ADAH", "ADAC" };
if( std::find( names.begin(), names.end(), name ) != names.end() )
cout<<"Call! Good hand!";
The thing is that most probably you will need this list of names again anyway (when you write a real program that does something usefull)
答案 1 :(得分:2)
The problem is that
if (name == "AHAH" || "ADAD"..)
Does not mean if name equals "AHAH" OR name equals "ADAD" but if (name == "AHAH") OR "ADAD". The latter is a char *
implicitly converted to bool
. Since the pointer is not null converts always to true. Hence the result.
答案 2 :(得分:2)
Instead of:
if(name == "AHAH" || "ADAD" ...
You want something like:
if((name == "AHAH") || (name == "ADAD") ...
答案 3 :(得分:2)
You need to write your if statement like so:
if ( name == "AHAH" || name == "ABCD" || ...etc... )
{
cout << "Call, good hand!";
}
else if ( name == "2H2H" )
{
cout << "Rase";
}
When you write your if statement like you did, you create pointers to char and since the char * is not NULL it has a value that is non-zero and therefore evaluates as True.