Advertisement
Advanced C++, Strings & string_view

What is std::format (C++20) and how does it improve string formatting?

Short answer

std::format provides Python-style, type-safe, positional string formatting that returns a std::string, replacing error-prone printf (no format/argument mismatches) and verbose iostream manipulators.

Save C++ mock interview
Advertisement
AModel answer
std::format provides Python-style, type-safe, positional string formatting that returns a std::string, replacing error-prone printf (no format/argument mismatches) and verbose iostream manipulators. It's extensible for user types via formatter specializations and is generally faster and safer than the alternatives.
std::string s = std::format("{} + {} = {}", 2, 3, 5);
Real-world example
Replacing sprintf with std::format removes format-string vulnerabilities and type mismatches.
Likely follow-ups
  • Why is std::format safer than printf? | How do you format custom types?
Related topics