C++ - Formatting (std::format)

Overview

Estimated time: 40–60 minutes

Use std::format for fast, safe, Python-like formatting. Learn format specifiers, chrono formatting, and tips vs iostreams.

Learning Objectives

  • Format strings, numbers, and chrono time points with std::format.
  • Understand alignment, width, precision, and custom specifiers.

Prerequisites

Basics

#include 
#include 
int main(){
  std::cout << std::format("Hello, {}! The answer is {}\n", "world", 42);
}

Width, alignment, precision

#include 
#include 
int main(){
  std::cout << std::format("|{:^10}|{:>8.2f}|\n", "hi", 3.14159);
}

Chrono formatting

#include 
#include 
#include 
int main(){
  using namespace std::chrono;
  auto now = system_clock::now();
  std::cout << std::format("{}\n", now); // ISO-like timestamp
}

Common Pitfalls

  • Ensure your standard library supports std::format (libstdc++ needed recent versions or fmtlib fallback).
  • std::format throwing on invalid format strings—validate or test formats.

Checks for Understanding

  1. How do you center text in a field?
  2. How do you print a time_point with std::format?
Show answers
  1. Use {:^N} where N is width.
  2. Include and pass the time_point to std::format with {}.

Exercises

  1. Format a table of names and scores with alignment.
  2. Print the current date/time in a custom layout using chrono formatting flags.