I'm trying to use a conditional statement that does one thing in one condition but does two things if the other condition applies.
Consider the following:
( h >= 0 && h < 24 ? hour = h : hour = 0, cout << "Invalid Hour Detected\n")
If "h" is set to 25, it sets "hour" to 0 correctly. If "h" is set to 12, it correctly sets "hour" to 12.
The problem is that it outputs "Invalid Hour Detected" for both true and false conditions. I only want it to output if the conditions aren't met.
Essentially, I'm wondering if it is possible in a conditional statement to do two things for one condition.
Also tried:
( h >= 0 && h < 24 ? hour = h : hour = 0 && cout << "Invalid Hour Detected\n")
but that didn't run the cout on either case.
If you really want to do this, add proper parentheses and invert the order of the assignment and the output insertion (when using the comma operator, the value of the left expression is discarded):
( h >= 0 && h < 24 ) ? ( hour = h ) : (std::cout << "Invalid Hour Detected\n", hour = 0);
However, my advice is to make your code readable and abandon this kind of coding style.