Let's say I want to print the number args if they are > 1 or "none" if they are <= 1. The only way I know how to do this is:
cout << "number of args: ";
if (argc > 1)
cout << argc - 1;
else
cout << "none";
cout << endl;
But then I can't chain the <<
operator. Ideally, I would like to be able to do something like:
cout << "number of args: "
<< argc > 1 ? argc - 1 : "none"
<< endl;
But this isn't possible because the types from a ternary if are different.
Ideas?
The simple way. Handle with a string.
std::cout << "number of args: "
<< (argc > 1 ? std::to_string(argc - 1) : "none")
<< std::endl;
It has some superfluous cost to change the string. But it is easy to read and maintain if it is used once. And the reason the parentheses are required is that the shift operator(<<) has higher precedence than ternary conditional operator(?:) or relational operators (>).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With