如何在三元条件运算符中添加换行符和串联? : 在 C++ 中

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

我想用三元条件运算符重写这段代码? : 在 C++ 中,但我不能添加新行(这里用 endl 表示)或连接空字符串

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

什么时候使用此代码

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

它没有产生正确的输出 如果我将 10 分配给 n,它会生成“@”(不带双引号),如果我将 11 分配给 n

,它会生成“,@”

您不能将字符串文字与整数相加。您应该首先构建所需的输出字符串,例如,使用 std::to_string.

改变

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

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

要扩展 acraig5075 的答案(C++ 没有用于将字符串连接到整数的运算符 +,尽管可以编写),可以

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

更清楚地打印 n,然后是 space 或新行,具体取决于 n 的值。

cout << n << (n % 10 ? " ": endl);  // if remainder is not zero put " "