CKTIS / C++
std::ios::boolalpha — read and write Boolean names
Set the `std::ios::boolalpha` flag with `setf` to read and write `bool` values using the stream’s locale-specific names rather than numeric representations.
Version: ISO C++23; implementation support may vary
Syntax
#include <iostream>
// Inside a function:
const auto previous = std::cout.setf(std::ios::boolalpha);
std::cout << true;
std::cout.flags(previous);std::ios::boolalpha is a format flag of type std::ios_base::fmtflags, not a function. std::ios is an alias for std::basic_ios<char>. Both the flag and the member function setf are declared in std::ios_base and available through inheritance.
std::cout.setf(std::ios::boolalpha) sets that flag without changing the others and returns the entire previous set of flags. The two-argument overload setf(flags, mask) replaces only the bits selected by the mask. The call itself prints nothing: a later << inserts the bool value. With the classic locale, this gives true or false instead of the default 1 or 0. Integers such as the int literal 1 are still printed as numbers.
The setting belongs to that stream and stays in effect after the next insertion. Use unsetf(std::ios::boolalpha) to clear just that flag, or flags(previous) to restore all the saved flags. The free function std::boolalpha, used as in std::cout << std::boolalpha, sets the same flag. The example calls setf directly instead.
On an input stream, the same flag makes >> for bool match the names supplied by that stream’s std::numpunct locale facet. If parsing finds no unique match, it sets failbit. Setting the flag on std::cout does not change std::cin.
Examples
#include <iostream>
#include <locale>
int main() {
std::cout.imbue(std::locale::classic());
std::cout << true << ' ' << false << '\n';
const auto previous = std::cout.setf(std::ios::boolalpha);
std::cout << true << ' ' << false << '\n';
std::cout.flags(previous);
std::cout << true << ' ' << false << '\n';
}Result
1 0 true false 1 0
`std::locale::classic()` fixes the spellings to `true` and `false`. The program prints the values before setting the flag, after setting it, and after restoring the previous flags.
Related lessons
- C++ · Lesson 5 · Advanced · Version: 3
Sources
- Working Draft, Standard for Programming Language C++ (WG21 N4950)
- [iosfwd.syn] Header <iosfwd> synopsis
- [ios.overview] Class template basic_ios overview
- [ios.fmtflags] Type ios_base::fmtflags
- [fmtflags.state] State functions
- [basic.ios.cons] Constructors and initial stream state
- [fmtflags.manip] fmtflags manipulators
- [ostream.inserters.arithmetic] Arithmetic inserters
- [facet.num.put.virtuals] num_put virtual functions
- [facet.num.get.virtuals] num_get virtual functions
- [facet.numpunct.virtuals] numpunct virtual functions
- [locale.statics] Static members of locale