a concerned citizen a concerned citizen - 3 months ago 11
C++ Question

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

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++.

Answer

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.)