[英]C++, ternary operator, std::cout
How to write the following condition with a ternary operator using C++如何使用 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.取决于
result1, result2
等是什么类型。
expressionC? expression1: expression2
expressionC? expression1: expression2
isn't valid for all types of expression1
and expression2
. expressionC? expression1: expression2
并非对所有类型的expression1
和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:现在,如果
result
是字符串,那么你可以这样做:
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
condition? true-value: false-value
. condition? true-value: false-value
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.