【问题标题】:Ternary conditional operator inside std::cout [closed]std::cout 内的三元条件运算符 [关闭]
【发布时间】:2020-08-21 10:37:44
【问题描述】:

这是我的代码:

std::cout << "The contaner is " << (!container)?"not":; "empty";

这显然行不通,但我希望现在这个想法很清楚。我想打印"The container is empty",如果bool containerfalse,则在"empty" 之前添加"not"

我想知道这是否可能,或者我是否必须写一些类似的东西:

if(container) std::cout ...;
else std::cout ...; 

【问题讨论】:

  • 请不要假设事情是显而易见的,而是应该发布minimal reproducible example 和编译器错误。通过一些(非常讨厌的)黑客,我确信这条线可以工作。
  • 请注意,您的三元运算符中间似乎还有一个杂散分号。

标签: c++ cout conditional-operator


【解决方案1】:

你快到了。三元运算符需要else结果,你可以使用空字符串"",然后,由于优先级问题,你需要用括号封装表达式:

std::cout << "The contaner is " <<  (!container ? "not" : "") << "empty";

【讨论】:

    【解决方案2】:

    可以在非空的情况下添加空字符串。

    std::cout << "The container is " << (!empty ? "not ": "") << "empty";
    

    或者把聪明程度调低一点,我个人觉得更易读,

    std::cout << "The container is " << (empty ? "empty": "not empty");
    

    【讨论】:

    • ... 一个聪明的编译器会将const char* 设为“空”点,指向“非空”内的“空”。
    • @TedLyngmo:但是当人工完成时会混淆:"not empty" + (empty ? 4 : 0) :-)
    • @Jarod42 :-) 确实!
    【解决方案3】:

    当所有其他方法都失败时,只需使用 if 语句:

    std::cout << "The contaner is ";
    if (!container)
        std::cout << "not ";
    std::cout<< "empty";
    

    我个人更喜欢使用条件运算符,因为它更易于阅读。当您要显示的事物的类型不同时,这也适用。条件运算符要求将两种情况都转换为通用类型,这样!container ? "not" : 1 之类的东西就不起作用了。

    【讨论】:

      【解决方案4】:

      试试...&lt;&lt; (!container ? "not" : "") &lt;&lt; "empty"

      【讨论】:

      猜你喜欢
      • 2011-09-30
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多