"if" condition always evaluates to "true"

c++ if-statement

185 观看

4回复

6 作者的声誉

I am running a series of if/ else if / else statements using strings, and regardless of the user input the if is always returning true:

All of the variables have been declared earlier in the code. For some reason, every time I run this code it says the first if statement is true, regardless of user input. What am I doing wrong"

作者: Weylin 的来源 发布者: 2017 年 9 月 15 日

回应 4


3

50434 作者的声誉

if (elementLookup == "H" || "Hydrogen" || "hydrogen")

This is three tests, OR'ed together.

The first test, elementLookup == "H", tests the string elementLookup for equality with "H".

The other two tests test a string literal ("Hydrogen" / "hydrogen") for being non-null.

Which is always true.

What you wanted is:

if (elementLookup == "H" || elementLookup == "Hydrogen" || elementLookup == "hydrogen")
作者: DevSolar 发布者: 2017 年 9 月 15 日

0

626 作者的声誉

You have to change the if condition

    if (elementLookup == "H" || elementLookup == "Hydrogen" || elementLookup == "hydrogen") {

        cout << "Atomic Number: " << H_NUMBER << endl << endl;
        cout << "Atomic Mass: " << H_MASS << endl << endl;

    }
    else if (elementLookup == "He" || elementLookup == "Helium" || elementLookup == "helium") {
        cout << "Atomic Number: " << HE_NUMBER << endl << endl;
        cout << "Atomic Mass: " << HE_MASS << endl << endl;
    }

    else if (elementLookup == "Li" || elementLookup == "Lithium" || elementLookup == "lithium") {
        cout << "Atomic Number: " << LI_NUMBER << endl << endl;
        cout << "Atomic Mass: " << LI_MASS << endl << endl;
    }

For every condition a check has to be made.

if (elementLookup == "H" || "Hydrogen" || "hydrogen") 

This means first a condition check for equality is made. After which "Hydrogen/hydrogen" is not a condition check it always turns to be a logical "1" / true. As it has some value in it. So the final || ORed will be true always

作者: Sathiya 发布者: 2017 年 9 月 15 日

-1

22 作者的声誉

Here it happens because of OR condition. "Hydrogen" is NOT-NULL so OR condition will be always true so each time block of IF will be executed.

作者: Piyush Sonani 发布者: 2017 年 9 月 15 日

0

1 作者的声誉

It seems that there is a confusion with syntax. To check the value of elementLookup the statement should be:

    if (elementLookup == "H" || elementLookup == "Hydrogen" || elementLookup == "hydrogen") {
    //Rest of your code

Lets take an example to understand why if condition always evaluates to true: The statement if(variable) will evaluate to false only if variable is either 0 or NULL. Since there are other strings in your if statement, ORing them always evaluates to 1. Hence its always true.

作者: avi 发布者: 2017 年 9 月 15 日
32x32