C++, ternary operator, std::cout

纵饮孤独 提交于 2020-01-23 04:52:11

问题


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

回答1:


Depends on what type is result1, result2 etc.

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 results 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




回答2:


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



来源:https://stackoverflow.com/questions/6611030/c-ternary-operator-stdcout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!