Formatting Output
Stream manipulators (<iomanip>)
| Manipulator | Effect | Sticky? |
|---|---|---|
std::fixed | fixed-point notation | yes |
std::setprecision(n) | n digits (after the point with fixed) | yes |
std::setw(n) | minimum field width for the next item only | no |
std::left / std::right | alignment within setw | yes |
std::setfill(c) | padding character | yes |
std::boolalpha | print true/false | yes |
std::hex, std::dec, std::oct | number base | yes |
std::showpos | show + on positive numbers | yes |
"Sticky" settings stay until you change them.
std::cout << std::fixed << std::setprecision(2) << 1695.0; // 1695.00
std::cout << std::setw(10) << "Rent" << '|'; // " Rent|"
std::format (C++20, <format>) ✅
Python-style formatting that returns a std::string:
std::format("{} is {} years old", name, age)
std::format("{:.2f}", 3.14159) // "3.14"
std::format("{:>10}", "Rent") // right-align in width 10
std::format("{:<10}", "Rent") // left-align
std::format("{:^10}", "Rent") // center
std::format("{:08.2f}", 12.5) // "00012.50"
std::format("{:x}", 255) // "ff"
std::format("{:,}", ...) // ❌ no thousands separator by default
Placeholders: {} in order, or {0}, {1} by position.
std::print / std::println (C++23, <print>)
std::println("Total: {:.2f}", total); // format + print + newline
Requires a recent compiler (GCC 14+, Clang 18+ with libc++, MSVC 2022 17.7+).
Choosing
- Quick output:
cout << - Tables and numbers:
std::format/std::print— clearer and type-safe - Avoid
printfin new C++ code (not type-safe)
Example
#include <format>
#include <iomanip>
#include <iostream>
#include <string>
int main() {
double pi = 3.14159265;
std::cout << "default: " << pi << '\n';
std::cout << "fixed 2: " << std::fixed << std::setprecision(2) << pi << '\n';
std::cout << std::left << std::setw(12) << "Item" << std::right << std::setw(10) << "Amount" << '\n';
std::cout << std::setfill('-') << std::setw(22) << "" << std::setfill(' ') << '\n';
std::cout << std::left << std::setw(12) << "Rent" << std::right << std::setw(10) << 15000.0 << '\n';
std::cout << std::left << std::setw(12) << "Groceries" << std::right << std::setw(10) << 3250.5 << '\n';
std::cout << "hex of 255: " << std::hex << 255 << std::dec << ", back to decimal: " << 255 << '\n';
// C++20 std::format
std::string name = "Asha";
int age = 24;
std::cout << std::format("{} is {} years old\n", name, age);
std::cout << std::format("[{:<8}] [{:>8}] [{:^8}]\n", "left", "right", "mid");
std::cout << std::format("Balance: Rs. {:.2f}\n", 12345.678);
std::cout << std::format("Zero padded: {:06d}, hex: {:#x}\n", 42, 255);
std::cout << std::format("{1} before {0}\n", "second", "first");
return 0;
}
/* Output:
default: 3.14159
fixed 2: 3.14
Item Amount
----------------------
Rent 15000.00
Groceries 3250.50
hex of 255: ff, back to decimal: 255
Asha is 24 years old
[left ] [ right] [ mid ]
Balance: Rs. 12345.68
Zero padded: 000042, hex: 0xff
first before second
*/