Ace Ebert
Ace Ebert

Reputation: 81

String comparing to constant with if-else statement. Skipping second if/else

I seem to be running into an issue. While trying to get input based off of A.M./P.M. entry,my if else statement is having some sort of logic error. I've never really done this sort of thing (I'm a bit new to c++) so help would be appreciated.

cout << "What time was the dose administered? (Round to hour): ";
cin >> time;
cout << "A.M./P.M.? ";
cin >> ap;

cout << ap;

if (ap == "A.M.", "am"){
    ap = "A.M.";
}
else if (ap == "P.M.", "pm"){
    ap = "P.M.";
}
else { cout << "This is not a valid entry.";
}

"ap" is a string. No matter what is entered, the result is "A.M."

Side note: Originally, it would only print "P.M." but both statements were orignally "if", when I changed it to "if else" it began printing "A.M." only.

Upvotes: 0

Views: 83

Answers (1)

Tony Delroy
Tony Delroy

Reputation: 106126

This...

ap == "A.M.", "am"

...under the rules of operator precedence, is equivalent to...

"am"

...which in a boolean context undergoes standard conversion to true (via a non-0 pointer).

That's because the comma operator evaluates the sub-expression on its left - namely ap == "A.M." - and while any side-effects of that evaluation are enacted the actual value of the sub-expression is then discarded and the sub-expression on the right - namely "am" - is evaluated and used instead.

You should instead use:

if (ap == "A.M." || ap == "am")

(The C++ Standard allows the keyword "or" as an alternative to ||, but famously Microsoft's compiler doesn't support it without an extra command-line argument, so in practice it's best avoided for portable code.)

Upvotes: 1

Related Questions