CKTIS / C++
`std::basic_ios::setf`: setting stream formatting flags
`setf` changes a stream's formatting flags. Use `std::ios::boolalpha` to print `bool` values as `true` and `false` in the classic locale.
Version: ISO C++23; implementation support may vary
Syntax
// Declared in std::ios_base (<ios>); inherited by std::basic_ios.
std::ios_base::fmtflags setf(std::ios_base::fmtflags flags);
std::ios_base::fmtflags setf(std::ios_base::fmtflags flags,
std::ios_base::fmtflags mask);std::basic_ios::setf is an inherited member function: both overloads are declared in std::ios_base. std::ios is an alias for std::basic_ios<char>, so std::ios::boolalpha names the same inherited flag as std::ios_base::boolalpha.
setf(flags) turns on the specified bits and leaves the others alone. setf(flags, mask) replaces only the bits selected by mask with the corresponding bits from flags. For example, use out.setf(std::ios_base::hex, std::ios_base::basefield) to change the integer base without leaving the previous base flag set. Both overloads return the full previous flag set as std::ios_base::fmtflags, not an error code or a stream reference.
std::cout.setf(std::ios::boolalpha) does not print anything. The stream insertion operator << uses the flag when it later writes a bool. In the classic locale the result is true or false instead of the usual 1 or 0; another locale can use different names. std::cout << std::boolalpha sets the same flag using a non-member manipulator, which the example does not use. The flag does not change how the integers 1 and 0 are printed.
The flag stays set on that stream after <<. Use out.unsetf(std::ios::boolalpha) to clear just that flag, or out.flags(previous) to restore the entire saved flag set.
Examples
#include <ios>
#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
The program explicitly selects `std::locale::classic()`. The expected lines are `1 0`, then `true false`, then `1 0` again after the flags are restored.
Related lessons
- C++ · Lesson 5 · Advanced · Version: 3
Sources
- C++ working draft — ios_base state functions [fmtflags.state]
- C++ working draft — Class template basic_ios overview [ios.overview]
- C++ working draft — Header <iosfwd> synopsis [iosfwd.syn]
- C++ working draft — fmtflags manipulators [fmtflags.manip]
- C++ working draft — Arithmetic inserters [ostream.inserters.arithmetic]
- C++ working draft — num_put virtual functions [facet.num.put.virtuals]
- C++ working draft — Class template numpunct [locale.numpunct]