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
- C++ - Coroutines (sequence context)
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
- How do you center text in a field?
- How do you print a time_point with std::format?
Show answers
- Use
{:^N}
where N is width. - Include
and pass the time_point to std::format with{}
.
Exercises
- Format a table of names and scores with alignment.
- Print the current date/time in a custom layout using chrono formatting flags.