0

I want to rewrite this code using ternary conditional operator ? : in c++ but I can't add new line (that is expressed by endl here) or concatenate the empty string

if (n % 10 == 0) {cout << n << endl;}
else {cout << n << " ";}

when is use this code

cout << (n % 10 == 0 ? n + "\n" : n + " ");

it doesn't produce the correct output it produces "@" (without double quotes) if I assign 10 to n and produce ",@" if I assign 11 to n

Mansour
  • 3
  • 1

3 Answers3

4

To expand on acraig5075's answer (C++ has no operator+ to concatenate a string to an integer, though it could be written), one could

cout << n << (n % 10 == 0 ? "\n" : " ");

Makes it clearer it prints n, then either a space or a new line, depending on n's value.

Uri Raz
  • 435
  • 1
  • 3
  • 15
  • 2
    Whilst I really would like it if this worked, it doesn't. `std::endl` and `" "` don't have a common type. Perhaps `"\n"`? – Caleth Jan 06 '20 at 09:28
  • I got this error "cannot determine which instance of function template "std::endl" is intended" – Mansour Jan 06 '20 at 09:29
  • My fault for not trying to compile it, replaced endl in my answer with "\n". – Uri Raz Jan 06 '20 at 09:35
  • 1
    Which you probably wanted to do anyway: https://stackoverflow.com/questions/213907/c-stdendl-vs-n – CompuChip Jan 06 '20 at 09:38
2

You can't add a string literal to an integer. You should instead first build the desired output string by, for example, using std::to_string.

Change

cout << (n % 10 == 0 ? n + "\n" : n + " ");

To

cout << (n % 10 == 0 ? std::to_string(n) + "\n" : std::to_string(n) + " ");
acraig5075
  • 10,588
  • 3
  • 31
  • 50
0
cout << n << (n % 10 ? " ": endl);  // if remainder is not zero put " "