C++ 如果变量值为零,则避免将变量传递给 std::cout

C++ Avoid passing variable to std::cout if its value is zero

假设我有一个变量,double x,作为一些计算的结果,它可以有任何值,包括零,我需要它传递给 std::cout。如果 x 的值为零,我怎样才能避免打印?

例如,如果 x,这将打印 1+<value_of_x>,否则只是 1:

std::cout << (x ? "1+" : "1") << x << '\n';

除了x,还有其他方法可以做到吗?像下面这样的废话:

std::cout << (x ? ("1+" << x) : "1") << '\n';

我应该补充一点,我在 C++ 方面并不先进。

如果x为0,不打印:

if (x != 0)
    std::cout << x << '\n';

任何进一步的变化应该是不言而喻的。

你可以说

std::cout << (x ? "1+" + std::to_string(x) : "1") << '\n';

但是

if (x)
    std::cout << "1+" << x << '\n';
else
    std::cout << "1" << '\n';

可能更具可读性。
(我认为这主要是个人喜好问题。)

使用 if 语句将是一种简单易读的方法:

if (x)
    std::cout << "1+" << x;
else
    std::cout << "1";
std::cout << '\n';

甚至:

std::cout << "1";
if (x) std::cout << "+" << x;
std::cout << '\n';

但是,如果你真的想打印出内联值,你可以定义一个自定义 operator<< 来格式化你想要的值:

struct to_coefficient_str
{
    double m_value;

    to_coefficient_str(double value) : m_value(value) {}

    void print(std::ostream &out) const
    {
        out << "1";
        if (m_value)
            out << "+" << m_value;
    }
};

std::ostream& operator<<(std::ostream &out, const to_coefficient_str &ce)
{
    ce.print(out);
    return out;
}

那么你可以这样使用它:

std::cout << to_coefficient_str(x) << '\n';