bool one = true;
bool two = false;
bool three = true;
bool four = false;
cout << boolalpha;
cout << "value of one : " << one << endl;
cout << "value of two : " << two << endl;
cout << "value of three : " << three << endl;
cout << "value of four : " << four;
When I run this code, the values of `one` and `two` get printed out as `true` and `false`. I want the values of `three` and `four` to be printed as `1` and `0`, but they are printed out as `true` and `false` instead.
I'm new to C++ and can't figure out how to reverse the effect of the `boolalpha`.
Asked
Active
Viewed 178 times
0

Remy Lebeau
- 555,201
- 31
- 458
- 770

Luigi_2000
- 17
- 2
-
2Use `std::noboolalpha`? – Jason Sep 28 '22 at 12:49
-
2`std::cout << std::noboolalpha`: https://en.cppreference.com/w/cpp/io/manip/boolalpha – Yksisarvinen Sep 28 '22 at 12:50
-
generic dupe but it doesn't have the better solution for this case: https://stackoverflow.com/questions/2273330/restore-the-state-of-stdcout-after-manipulating-it – NathanOliver Sep 28 '22 at 12:51
-
This one explains setting and resetting boolalpha: https://stackoverflow.com/questions/29383/converting-bool-to-text-in-c – Yksisarvinen Sep 28 '22 at 12:52
-
There is also Boost [IO State Saver](https://www.boost.org/doc/libs/1_80_0/libs/io/doc/html/io.html) which can be used to save the current stream flags state, then you can do whatever flag manipulation you need, and the restore the state. (Don't have to use Boost to do this; could do it manually. Boost just makes it convenient.) – Eljay Sep 28 '22 at 13:30
-
1If avoiding iostreams and sticky flags is an option, I'd use the [fmt](https://fmt.dev/latest/index.html) library: https://godbolt.org/z/oo8jdqs7x – rturrado Sep 28 '22 at 14:42
1 Answers
5
How do I reverse the effect of "cout << boolalpha" in c++?
You can use std::noboolalpha
as given on std::boolalpha's documentation:
std::ios_base& noboolalpha( std::ios_base& str ); (2)
- Disables the boolalpha flag in the stream
str
as if by callingstr.unsetf(std::ios_base::boolalpha)
(emphasis mine)
This means you can write the following:
std::cout << std::noboolalpha;
std::cout << "value of three : " << three << std::endl;
std::cout << "value of four : " << four;

Jason
- 36,170
- 5
- 26
- 60
-
I was commenting "What does this comment add to the already existing comment?" :P – Enlico Sep 28 '22 at 12:59
-