C++ bool 返回 0 1 而不是真假

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8261674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:16:57  来源:igfitidea点击:

C++ bool returns 0 1 instead of true false

c++overloadingboolean

提问by xBlue

I have overloaded equals (including == and !=) that checks if two objects are equals and then returns a boolean.

我重载了 equals(包括 == 和 !=),它检查两个对象是否相等,然后返回一个布尔值。

Unfortunately, it prints 0 or 1. I know it's correct but I can't figure out the way to make it to print true or false for readability purposes.

不幸的是,它打印 0 或 1。我知道它是正确的,但我不知道如何让它打印 true 或 false 以提高可读性。

I've even tried:

我什至试过:

if (a.equals(b))
{
    return true;
}

return false;

However, C++ is stubborn enough to output 0 or 1.

但是,C++ 固执到输出 0 或 1。

Any help would be appreciated.

任何帮助,将不胜感激。

Edit - Print is done:

编辑 - 打印完成:

cout << "a == b is " << (a == b) << endl;

Desired output is

期望的输出是

a == b is true

a == b 为真

回答by Luchian Grigore

You can use std::boolalpha:

您可以使用std::boolalpha

Sets the boolalpha format flag for the str stream.

When the boolalpha format flag is set, bool values are inserted/extracted as their names: true and false instead of integral values.

This flag can be unset with the noboolalpha manipulator.

The boolalpha flag is not set in standard streams on initialization.

为 str 流设置 boolalpha 格式标志。

当 boolalpha 格式标志被设置时, bool 值被插入/提取为它们的名称:true 和 false 而不是整数值。

可以使用 noboolalpha 操纵器取消设置此标志。

初始化时标准流中未设置 boolalpha 标志。

std::cout.setf(std::ios::boolalpha);
std::cout << true;

or

或者

std::cout << std::boolalpha << true;

回答by John Zwinck

You need to use std::boolalpha:

您需要使用std::boolalpha

cout << boolalpha << yourthing() << endl;

回答by B?ови?

You need to use std::boolalphato print true/false :

您需要使用std::boolalpha来打印 true/false :

#include <iostream>

int main()
{
  std::cout << std::boolalpha << true << std::endl;
}

回答by Mark Ransom

If you need to do this outside of a stream output <<, it's a simple ternary expression:

如果您需要在流输出之外执行此操作<<,则它是一个简单的三元表达式:

std::string str = (a == b) ? "true" : "false";