C ++, ternary operator, std :: cout

How to write the following condition with a ternary operator using C ++

int condition1, condition2, condition3; int / double result; //int or double .... std::cout << ( condition1: result1 : "Error" ) << ( condition2: result2 : "Error" ) << ( condition3: result3 : "Error")...; 
+8
c ++ ternary-operator conditional printing
source share
2 answers

Depends on the type of result1, result2 , etc.

expressionC ? expression1 : expression2 expressionC ? expression1 : expression2 not valid for all types expression1 and expression2 . They must be converted to a general type, roughly speaking (exact rules and exceptions can be read in the standard). Now, if result are strings, you do it like this:

 std::cout << ( condition1 ? result1 : "Error" ) ^^^ << ( condition2 ? result2 : "Error") ^^^ << etc. 

But if the results are integers, for example, you cannot do this.

NTN

+13
source share

Try using condition ? true-value : false-value condition ? true-value : false-value .

+1
source share

All Articles