英文:
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 << 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
答案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 << n << (n % 10 == 0 ? "\n" : " ");
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 << (n % 10 == 0 ? n + "\n" : n + " ");
To
cout << (n % 10 == 0 ? std::to_string(n) + "\n" : std::to_string(n) + " ");
答案3
得分: 0
cout << n << (n % 10 ? " " : endl); // 如果余数不为零则输出空格,否则换行。
英文:
cout << n << (n % 10 ? " ": endl); // if remainder is not zero put " "
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论