Modern Formatting with std::format (C++20)
C++20's std::format (from <format>) finally gives C++ Python-style {} placeholders: std::format("{} + {} = {}", 1, 2, 3) builds the string directly — type-safe like iostreams but far more compact than manipulator chains. Format specs inside the braces control width, alignment, precision, and base ({:08.2f}, {:x}, {:>10}).
The catch is compiler support: GCC 13+, Clang 14+, and MSVC 19.29+ cover it, older toolchains don't — check __cpp_lib_format or your compiler version before depending on it. Where supported, prefer it over both iomanip soup and unsafe printf.
{} placeholders in order
std::format("{} is {}", name, age) substitutes arguments left to right — no counting codes, no type mismatches possible.
Format specs after a colon
{:.2f} fixes two decimals, {:>8} right-aligns in width 8, {:04d} zero-pads — one compact grammar for everything iomanip did verbosely.
Type-safe by construction
Mismatched types fail at compile time, unlike printf's runtime undefined behavior on a wrong % code.
Check support first
Needs a recent compiler (g++ 13+ with -std=c++20); on older ones, fmt::format from the {fmt} library is the near-identical fallback.
#include <format>#include <iostream> int main() { std::string msg = std::format("{} scored {:.1f}", "Ada", 97.25); std::cout << msg << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.