【问题标题】:C++, ternary operator, std::coutC++,三元运算符,std::cout
【发布时间】:2011-09-30 11:04:21
【问题描述】:

如何使用 C++ 用三元运算符编写以下条件

int condition1, condition2, condition3;
int / double result; //int or double
....
std::cout << ( condition1: result1 : "Error" ) 
          << ( condition2: result2 : "Error" )
          << ( condition3: result3 : "Error")...;

【问题讨论】:

  • 三元运算符是 cond ? exp1 : exp2 。你用过: :除此之外,我觉得没什么好说的了!
  • @Diff:哦,是的,有,看我的回答

标签: c++ printing conditional ternary-operator


【解决方案1】:

取决于result1, result2等是什么类型

expressionC ? expression1 : expression2 并非对所有类型的expression1expression2 都有效。粗略地说,它们必须可以转换为通用类型(可以在标准中阅读确切的规则和例外情况)。现在,如果results 是字符串,那么你可以这样做:

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

但如果结果是整数,例如,你不能这样做。

HTH

【讨论】:

  • 那么将结果转换为字符呢?
  • @Johnas:不,那不行。 "Error" 的类型为 const char[6]charconst char[6] 是不同的不兼容类型
  • 感谢您的帮助和 cmets。
  • 从 C++11 开始,如果 result1 的类型是 int、double 或 to_string() 接受的其他类型,您可以执行 (condition1 ? to_string(result1) : string("Error"))。我不知道这是否是一个好习惯,但至少对于快速调试等来说应该没问题。虽然对 C++ 很陌生,如果我错了,请纠正我
  • @NotEnoughData 是的,您确实可以使用to_string,但是您的格式可能无法正常工作,例如使用scientific 将不起作用。
【解决方案2】:

尝试使用condition ? true-value : false-value

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多