Sam LaManna
Sam LaManna

Reputation: 425

C++ ignore a variable and prevent output

I have 2 variables one has a value of 5 the other has a value of 0. if i have:

cout << var1;      //the one with a value of 5
cout << var2;      //the one with a value of 0

is there a way to make the second variable not print anything if its value is 0 at that point in the code?

Upvotes: 1

Views: 606

Answers (2)

Sim
Sim

Reputation: 4184

Easiest way would be this operator (bool) ? (iftrue) : (iffalse);

std::cout << (var2 == 0) ? "" : var2;

This solution enables you to add more output after var2 even though var2 shall not be printed:

std::cout << (var2 == 0) ? "" : var2 << " i am after var2 in any case" << std::endl;

Upvotes: 0

Mysticial
Mysticial

Reputation: 471249

Just use an if-statement:

cout << var1;
if (var2 != 0)
     cout << var2;

Upvotes: 5

Related Questions