Is it possible to use logical operators within "Cout"? - C++

Asked

Viewed 83 times

4

I would like to know if you have how to use logical operators and/or ternary operator within the Cout, as well as is possible within the printf.


int main ()
{
   int n = 5;

   //Como fazer isso (Funciona)
   printf ("O numero %se maior que 5\n", n > 5?"":"nao ");

   //Utilizando cout (Nao funciona)
   cout << n > 5?"O numero e maior que 5":"O numero nao e maior que 5" << endl;

   return 0;
}

1 answer

9


What happens is that operators >> and << which are "shift right" and "shift left" are reset to the "Cout" object and work to "channel" the objects you want to put in the standard output.

Only that redefining an operator (override) does not change its priority - that is, since << has more priority than the >, he will be executed before - and from then on everything will go wrong.

To solve, simply place parentheses around the entire expression you want to play for Cout:

cout << (n > 5?"O numero e maior que 5":"O numero nao e maior que 5") << endl;

Now, the whole expression in parentheses is solved, and its result is that it is used with the <<.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.