cout 中的 C++ if-else 语句

标签 c++ if-statement ternary-operator cout ostream

我想做这样的事情:

ostream& table(ostream& os, myClass& obj, bool foo1, bool foo2) {
    os << (foo1 ? obj.getFoo1() : "") << (foo2 ? obj.getFoo2() : "");
    return os;
}

现在我的主要问题是,我不需要 else 语句。即使我不能在没有 else 的情况下使用三元运算符,我也需要像 "" 这样发送空格。我真的很想使用 "" 但我的 obj.getFoo 不返回任何字符串值(它返回一个整数)。对于整数,没有“空间”。

有没有办法在 cout 中获取 if-else 语句(显然没有 else)?

最佳答案

如果你使用 to_string 就可以做到:

ostream& table(ostream& os, myClass& obj, bool foo1, bool foo2) {
  os << (foo1 ? std::to_string(obj.getFoo1()) : "") 
     << (foo2 ? std::to_string(obj.getFoo2()) : "");

  return os;
}

LIVE DEMO

关于cout 中的 C++ if-else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33766209/

相关文章:

c++ - 在 C++ 中评估变量 if 语句

batch-file - 使用 If 语句和键盘输入的批处理文件

ruby - 有没有办法让这个 Ruby 三元运算正确评估?

c++ - 不评估两个参数的 Halide 'select'

c++ - 不允许不完整的类型 : stringstream

c++ - 对容器中项目的常量正确指针访问

c++ - 为什么 unsigned char 返回的值与 C++ 中的 signed char 相同?

python - While 循环、if-else 语句 : Guess my number game

javascript - 如何使用 if...else 子句重写它?

c++ - QLocalServer 不会启动传入连接