三元运算符中的 Cout 字符串和 int

Cout String and int in ternary operator

本文关键字:Cout 字符串 int 运算符 三元      更新时间:2023-10-16

我的c++代码中有一行内容如下:

cout<<(i%3==0 ? "Hellon" : i) ;//where `i` is an integer.

但是我收到此错误:

operands to ?: have different types 'const char*' and 'int

如何修改代码(使用最少字符)?

丑陋:

i%3==0 ? cout<< "Hellon" : cout<<i;

好:

if ( i%3 == 0 )
   cout << "Hellon";
else
   cout << i;

您的版本不起作用,因为:两侧表达式的结果类型需要兼容。

如果两个替代项的类型不兼容,则不能使用条件运算符。最清楚的是使用if

if (i%3 == 0)
    cout << "Hellon";
else
    cout << i;

尽管在这种情况下,您可以将数字转换为字符串:

cout << (i%3 == 0 ? "Hellon" : std::to_string(i));

一般来说,你应该尽量提高清晰度,而不是最小化字符;当你将来必须阅读代码时,你会感谢自己。

operator<<是重载的,并且两个执行路径不使用相同的重载。 因此,不能在条件之外<<

你想要的是

if (i%3 == 0) cout << "Hellon"; else cout << i;

这可以通过反转条件来缩短一点:

if (i%3) cout << i; else cout << "Hellon";

使用三元保存的更多字符:

(i%3)?(cout<<i):(cout<<"Hellon");
std::cout << i % 3 == 0 ? "Hello" : std::to_string(i);

但是,正如所有其他答案所说,您可能不应该这样做,因为它很快就会变成意大利面条代码。