三元运算符中的 Cout 字符串和 int
Cout String and int in ternary operator
我的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);
但是,正如所有其他答案所说,您可能不应该这样做,因为它很快就会变成意大利面条代码。
相关文章:
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么我的 cout 在输出中没有显示字符串?
- 使用 cout 运算符重载字符串
- C++ - 如何从上到下制作 4x4 矩阵和 cout 列(需要解密字符串)
- C++ 不能在cout中使用向量和字符串文字
- 使用字符串流加速 std::cout 日志记录
- C++ cout 不接受字符串或带 + 的字符串
- cout 切断 for 循环中的字符串开头
- 使用带有 std::cout 的单引号打印字符串实际上打印了数字
- 为什么cout输出内存地址不是字符串?
- 为什么我的 C++ 代码不能显示 cout 字符串
- 在COUT字符串期间,在控制台上闪烁光标
- C++ cout 字符串不起作用.请指教
- cout 字符串和向量在同一行中
- 如何更改对象的 cout 字符串
- 在 std::cout 字符串上崩溃
- cout 字符串和 c_str 在 C++ 中给出不同的值
- 在c++中使用字符串(搜索字符串,分割字符串,cout<<字符串)
- Flex cout字符串崩溃
- 三元运算符中的 Cout 字符串和 int