liveBook · Manning

Std::format

As explained in 100 C++ Mistakes and How to Avoid Them

std::format is a C++ standard-library function that produces a formatted string from a format string and typed arguments.

Mistake 20: relying on printf-style formatting makes type mismatches easy to introduce, while string streams make precise formatting awkward. std::format offers readable, fine-grained formatting with type-safe arguments. It can align output and enforce padding without manually converting values or managing a character buffer. section 4.3

Formatted student output

std::cout << std::format("{} is a student aged {} carrying a gpa of {:0^4}", dinah.name, dinah.age, dinah.gpa) << '\n'; The format specification produces a four-character, zero-padded GPA field: 4 becomes 4.00, 3.5 becomes 3.50, and 3.85 remains 3.85. section 4.3

Listing 4.7 Using std::format for fine-grained formatting functionality
struct Student {
    std::string name;
    int age;
    double gpa;
    Student(const std::string& n, int a, double g) : name(n), age(a), gpa(g) {}
};
 
int main() {
    Student dinah("Dinah", 26, 3.3);
    std::cout << std::format("{} is a student aged {} carrying a gpa of 
    {:0^4}", dinah.name, dinah.age, dinah.gpa) << '\n';     #1
    return 0;
}
#1 sprintf-like functionality with type-safe behavior

Compare the concise std::format version with the supplied sprintf and stringstream implementations. section 4.3

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Demonstrates format fields, width, padding, and type safety, but defers broader format-specifier details.
Examples
Uses a Student record to format a name, age, and GPA with consistent padding.
What you can do after
Apply it via std::format to produce aligned, padded strings without printf-style type-mismatch problems.
How it connects
Connects std::format with printf-style functions, string streams, std::print, and std::println.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.