C++ bool returns 0 1 instead of true false

47,553

Solution 1

You can use 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.

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

or

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

Solution 2

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

#include <iostream>

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

Solution 3

You need to use std::boolalpha:

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

Solution 4

This fixes it directly

std::cout << std::boolalpha << "a == b is " << (a == b) << '\n';

With this it covers it general without repeating std::boolalpha

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

Share:
47,553
xBlue
Author by

xBlue

Updated on December 03, 2021

Comments

  • xBlue
    xBlue over 2 years

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

    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.

    I've even tried:

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

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

    Any help would be appreciated.

    Edit - Print is done:

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

    Desired output is

    a == b is true