三元运算符中的Cout String和int

xan*_*xan 0 c++ string int

我的c++代码中的一行是:

cout<<(i%3==0 ? "Hello\n" : i) ;//where `i` is an integer.
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:

operands to ?: have different types 'const char*' and 'int
Run Code Online (Sandbox Code Playgroud)

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

Luc*_*ore 6

丑陋:

i%3==0 ? cout<< "Hello\n" : cout<<i;
Run Code Online (Sandbox Code Playgroud)

尼斯:

if ( i%3 == 0 )
   cout << "Hello\n";
else
   cout << i;
Run Code Online (Sandbox Code Playgroud)

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