Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 912
xBlue Avatar asked Nov 24 '11 19:11

xBlue


People also ask

Is bool true 1 or 0?

Boolean Variables and Data Type ( or lack thereof in C ) C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.

Is bool automatically true or false?

bool "bar" is by default true, but it should be false, it can not be initiliazied in the constructor. is there a way to init it as false without making it static?

What does bool function return in C?

In C, most things we think of as boolean are actually int (0 or 1). We prefer to use bool return type for functions which have 2 return values ( true or false ).


2 Answers

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; 
like image 197
Luchian Grigore Avatar answered Oct 21 '22 03:10

Luchian Grigore


You need to use std::boolalpha:

cout << boolalpha << yourthing() << endl; 
like image 28
John Zwinck Avatar answered Oct 21 '22 05:10

John Zwinck