简体   繁体   中英

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")...;

Depends on what type is result1, result2 etc.

expressionC? expression1: expression2 expressionC? expression1: expression2 isn't valid for all types of expression1 and expression2 . They must necessarily be convertible to a common type, roughly speaking (exact rules and exceptions can be read in the standard). Now, if result s are strings, then you do it like this:

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

But if results are integers, for example, you can't do it.

HTH

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM