0
0
CppHow-ToBeginner · 4 min read

How to Use std::format in C++20 for String Formatting

Use std::format in C++20 to create formatted strings by providing a format string and arguments, similar to Python's f-strings. Include <format> header and call std::format(format_string, args...) to get a formatted std::string.
📐

Syntax

The basic syntax of std::format is:

  • std::format(format_string, arg1, arg2, ...)
  • format_string contains text and replacement fields marked by curly braces {}.
  • Each {} is replaced by the corresponding argument formatted as specified.
  • You can add format specifiers inside braces, like {:d} for decimal or {:.2f} for floating-point precision.
cpp
std::string result = std::format("Hello, {}! You have {} new messages.", "Alice", 5);
💻

Example

This example shows how to use std::format to create a formatted string with different types of arguments.

cpp
#include <iostream>
#include <format>

int main() {
    std::string name = "Bob";
    int unread = 3;
    double pi = 3.14159;

    std::string message = std::format("Hello, {}! You have {} unread messages. Pi is approximately {:.2f}.", name, unread, pi);
    std::cout << message << std::endl;

    return 0;
}
Output
Hello, Bob! You have 3 unread messages. Pi is approximately 3.14.
⚠️

Common Pitfalls

Common mistakes when using std::format include:

  • Not including the <format> header.
  • Using a format string with mismatched or missing replacement fields for the arguments.
  • Trying to use std::format in compilers or environments that do not support C++20.
  • Incorrect format specifiers causing runtime exceptions.

Example of a mismatch error:

cpp
#include <format>

// Wrong: fewer replacement fields than arguments
// std::string s = std::format("Hello, {}!", "Alice", 42); // Throws std::format_error

// Correct:
std::string s = std::format("Hello, {}! You are number {}.", "Alice", 42);
📊

Quick Reference

Format SpecifierDescriptionExample
{}Default format for argumentstd::format("Hello, {}", "World")
{:d}Decimal integerstd::format("Number: {:d}", 42)
{:x}Hexadecimal (lowercase)std::format("Hex: {:x}", 255)
{:X}Hexadecimal (uppercase)std::format("Hex: {:X}", 255)
{:.2f}Floating point with 2 decimalsstd::format("Pi: {:.2f}", 3.14159)
{:>10}Right-align in 10 spacesstd::format("{:>10}", "text")
{:<10}Left-align in 10 spacesstd::format("{:<10}", "text")

Key Takeaways

Include <format> and use std::format with a format string and arguments to create formatted strings.
Replacement fields in the format string must match the number of arguments provided.
Use format specifiers inside braces to control number formatting, alignment, and precision.
std::format requires C++20 support in your compiler and standard library.
Mismatched format strings and arguments cause runtime exceptions.