CKTIS / C++
std::ios_base: formatting flags and precision
std::ios_base stores a stream's formatting state. Learn how the setf overloads differ, what precision means, and how to enable fixed and boolalpha safely while preserving settings for later restoration.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
std::ios_base::fmtflags setf(std::ios_base::fmtflags fmtfl);
std::ios_base::fmtflags setf(std::ios_base::fmtflags fmtfl, std::ios_base::fmtflags mask);
std::streamsize precision() const;
std::streamsize precision(std::streamsize prec);
stream.setf(std::ios_base::fixed, std::ios_base::floatfield);
stream.precision(2);
stream.setf(std::ios_base::boolalpha);std::ios_base stores formatting settings for an individual stream. std::ios_base::setf and std::ios_base::precision are member functions; std::ios_base::fixed and std::ios_base::boolalpha are fmtflags flags, not the manipulators std::fixed and std::boolalpha. Settings remain active until changed again.
setf(fmtfl) adds the specified bits without clearing others. setf(fmtfl, mask) first clears the bits selected by mask, then sets fmtfl & mask. Both overloads return the previous complete flag set. To select fixed-point notation, use setf(std::ios_base::fixed, std::ios_base::floatfield): merely adding fixed does not clear scientific; having both bits set selects hexadecimal floating-point notation.
precision() reads the precision, while precision(n) sets it and returns the previous value. In fixed mode, precision specifies digits after the decimal separator; in the default floating-point mode, it specifies significant digits. It does not change the stored numeric value. boolalpha enables textual insertion and extraction of bool; the names depend on the locale. With std::locale::classic(), they are true and false, rather than numeric output 1 and 0.
The example uses a local stream with std::locale::classic() to stabilize the decimal separator and Boolean names. It saves flags and precision, then restores them separately through flags(savedFlags) and precision(savedPrecision). When working with a shared stream, also arrange restoration if an exception occurs, for example with an RAII guard.
Examples
#include <iostream>
#include <locale>
#include <sstream>
int main() {
std::ostringstream out;
out.imbue(std::locale::classic());
const auto savedFlags = out.setf(
std::ios_base::fixed, std::ios_base::floatfield);
const auto savedPrecision = out.precision(2);
out.setf(std::ios_base::boolalpha);
out << 12.5 << ' ' << true << ' ' << false << '\n';
out.flags(savedFlags);
out.precision(savedPrecision);
out << 12.5 << ' ' << true << ' ' << false << '\n';
std::cout << out.str();
}
Result
12.50 true false 12.5 1 0
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.