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

c++ cout

87 просмотра

3 ответа

Suppose I have a variable, double x, as a result of some calculations, which can have any value, including zero, and I need it passed to std::cout. How can I avoid printing x if its value is zero?

As an example, this will print 1+<value_of_x> if x, else just 1:

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

Is there a way to make the same but for x? Something like the following nonsense:

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

I should probably add that I am not advanced in C++.

Автор: a concerned citizen Источник Размещён: 08.11.2019 11:30

Ответы (3)


3 плюса

Решение

You could say

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

but

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

is perhaps more readable.
(I consider this largely a matter of personal preference.)

Автор: molbdnilo Размещён: 20.08.2016 03:40

1 плюс

If x is 0, don't print it:

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

Any further variations should be self-evident.

Автор: Pete Becker Размещён: 20.08.2016 03:34

1 плюс

Using an if statement would be a simple and readable approach:

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

Or even:

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

But, if you really want to print out the value inline, you can define a custom operator<< to format the value however you want:

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;
}

Then you can use it like this:

std::cout << to_coefficient_str(x) << '\n';
Автор: Remy Lebeau Размещён: 20.08.2016 04:46
Вопросы из категории :
32x32