xBlue
xBlue

Reputation: 673

C++ bool returns 0 1 instead of true false

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

Upvotes: 35

Views: 56288

Answers (5)

Kenny Nelcon
Kenny Nelcon

Reputation: 11

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);

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308520

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

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

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258648

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;

Upvotes: 64

BЈовић
BЈовић

Reputation: 64283

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

#include <iostream>

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

Upvotes: 8

John Zwinck
John Zwinck

Reputation: 249582

You need to use std::boolalpha:

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

Upvotes: 8

Related Questions