用cout打印出布尔选项

Printing out bool options with cout

本文关键字:布尔 选项 打印 cout      更新时间:2023-10-16

我知道,如果您的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");