如何在C++中使用三元条件运算符添加换行和连接?

huangapple go评论74阅读模式
英文:

How to add newline and concatenation in ternary conditional operator ? : in c++

问题

Here's the code rewritten using the ternary conditional operator:

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

This code should produce the correct output.

英文:

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 &lt;&lt; n &lt;&lt; endl;}
else {cout &lt;&lt; n &lt;&lt; &quot; &quot;;}

when is use this code

cout &lt;&lt; (n % 10 == 0 ? n + &quot;\n&quot; : n + &quot; &quot;);

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

答案1

得分: 4

要扩展acraig5075的回答(C++没有用于将字符串连接到整数的operator+,尽管可以编写它),可以使用以下方式:

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

这使得它更清晰地打印出n,然后根据n的值打印出一个空格或换行符。

英文:

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 &lt;&lt; n &lt;&lt; (n % 10 == 0 ? &quot;\n&quot; : &quot; &quot;);

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

答案2

得分: 2

你不能将字符串字面值添加到整数上。相反,你应该首先构建所需的输出字符串,例如使用 std::to_string

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

更改为

cout << (n % 10 == 0 ? std::to_string(n) + "\n" : std::to_string(n) + " ");
英文:

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 &lt;&lt; (n % 10 == 0 ? n + &quot;\n&quot; : n + &quot; &quot;);

To

cout &lt;&lt; (n % 10 == 0 ? std::to_string(n) + &quot;\n&quot; : std::to_string(n) + &quot; &quot;);

答案3

得分: 0

cout << n << (n % 10 ? " " : endl); // 如果余数不为零则输出空格,否则换行。

英文:
cout &lt;&lt; n &lt;&lt; (n % 10 ? &quot; &quot;: endl);  // if remainder is not zero put &quot; &quot;

huangapple
  • 本文由 发表于 2020年1月6日 17:06:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609266.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定