用cout打印出布尔选项
Printing out bool options with cout
我知道,如果您的bool函数只打印出一些文本,那么有两种方法可以打印出结果。其中一个非常简单,就像这样:
#include <iostream>
using namespace std;
bool function(int x)
{
int y=5;
return x==y;
}
int main(void)
{
int a;
cin >> a;
if(function(a))
cout << "Equal to 5";
else
cout << "Not equal to 5";
}
我曾经知道在同一行中使用cout和bool在一行中打印一些"消息"的其他方法,但下面的解决方案并没有奏效。这是怎么回事?
cout << function(a) ? "Equal" : "Not equal";
我收到通知,被调用函数的函数总是返回true,这很奇怪。
根据编译器的不同,它可能会发出警告,告诉问题的具体内容
main.cpp:15:21: warning: operator '?:' has lower precedence than '<<'; '<<' will be evaluated first [-Wparentheses]
cout << function(a) ? "Equal" : "Not equal";
~~~~~~~~~~~~~~~~~~~ ^
main.cpp:15:21: note: place parentheses around the '<<' expression to silence this warning
cout << function(a) ? "Equal" : "Not equal";
^
( )
main.cpp:15:21: note: place parentheses around the '?:' expression to evaluate it first
cout << function(a) ? "Equal" : "Not equal";
main.cpp:15:26: warning: expression result unused [-Wunused-value]
cout << function(a) ? "Equal" : "Not equal";
正如@顺磁性羊角面包所说,用括号把它括起来。
cout << (function(a) ? "Equal" : "Not equal");
根据@WhozCraig的评论,解释就是命令。正如警告所说,首先评估<<
,结果是(cout << function(a)) ? "Equal : "Not Equal";
。这将返回"Equal"(或"Not Equal",无关紧要),从而导致随后的"expression result unused"警告。
我不确定这是否是你的意思,甚至是你需要的,但你考虑过使用std::boolalpha
吗?
std::cout << function(5) << ' ' << function(6) << std::endl;
std::cout << std::boolalpha << std::function(5) << ' ' << function(6) << std::endl;
输出:
1 0
true false
http://en.cppreference.com/w/cpp/io/manip/boolalpha
尝试
cout << (function(a) ? "Equal" : "Not equal");
相关文章:
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- Win32编译器选项和内存分配
- 一个关于在C++中重载布尔运算符的问题
- 提升精神:解析布尔表达式并简化为规范范式
- C/C++预处理器是否可以检测一些编译器选项
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 线程之间的布尔停止信号
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- 布尔比较运算符是如何在C++中工作的
- 变量定义到C++布尔值转换
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 隐式常量/非常量运算符布尔
- 通过选项卡的文本设置QTabWidget顺序
- 通过ccmake在cmake中缓存依赖选项
- 如何编写一个使用n倍三元条件语句的C++布尔函数
- Android :需要在 c++ NDK 中创建共享首选项对象并存储一些布尔值
- C++设计:具有布尔选项的函数
- 用cout打印出布尔选项
- 如何解析配置文件中的布尔选项