Use ternary operator to print various types on one line

I want the code not to look like this:

int x = ...;
cout << "x=";
if(x)
  cout << x;
else
  cout << "???";
cout<<"!";

I really want something like:

cout << "x=" << (x ? x : "???") << "!";

But this does not compile, as xthey "???"are incompatible / different types.

Is there any way to do this neatly?

+4
source share
1 answer

You can put coutin the ternary operator:

cout << "x="; 
(x ? cout << x : cout << "???") << "!";

Or use std::to_string()if your compiler supports C ++ 11:

cout << "x=" << (x ? std::to_string(x) : "???") << "!";

Live demo

+3
source

All Articles