std::format

Modern C++ string formatting made easy

🎯 What is std::format?

std::format is a modern C++20 feature that provides type-safe, efficient string formatting similar to Python's format strings. It replaces unsafe printf-style formatting with a cleaner, more readable syntax.


#include <format>
#include <iostream>

int main() {
    std::string name = "Alice";
    int age = 25;
    std::cout << std::format("Hello {}, you are {} years old!", name, age);
    return 0;
}
                                    

Output:

Hello Alice, you are 25 years old!

Key Features of std::format

🔒

Type Safe

Compile-time type checking prevents errors

std::format("{}", 42);  // ✅ Safe
📝

Easy Syntax

Clean, readable formatting syntax

std::format("Value: {}", x);

Efficient

Optimized performance over printf

// Fast string building
🎨

Flexible

Rich formatting options available

std::format("{:.2f}", 3.14159);

🔹 Basic Usage

String formatting with positional arguments enables clear and reusable text templates. Using libraries like <format> in C++20 or fmt, you define placeholders such as {} within a string. Arguments supplied to the format function fill these placeholders in order. For example, format("Hello, {}!", "World") produces "Hello, World!". This method avoids concatenation clutter, improves localization support, and enhances readability compared to traditional C-style printf specifiers.

#include <format>
#include <iostream>
#include <string>

int main() {
    // Basic formatting
    std::string result = std::format("Hello {}!", "World");
    std::cout << result << std::endl;
    
    // Multiple arguments
    int x = 10, y = 20;
    std::cout << std::format("{} + {} = {}", x, y, x + y) << std::endl;
    
    return 0;
}

Output:

Hello World!
10 + 20 = 30

🔹 Number Formatting

Advanced number formatting in C++ enables precise control over numeric output, including bases, alignment, and localization. Using std::format, you can format integers as hex ({:x}), control floating-point precision ({:.2f}), and add thousands separators. For example, std::format("{:#x}", 255) produces 0xff. This eliminates manual string manipulation and ensures consistent, readable output across different numeric types, which is crucial for financial, scientific, and debugging applications.

#include <format>
#include <iostream>

int main() {
    double pi = 3.14159265;
    
    // Decimal precision
    std::cout << std::format("Pi: {:.2f}", pi) << std::endl;
    
    // Hexadecimal
    int num = 255;
    std::cout << std::format("Hex: {:#x}", num) << std::endl;
    
    // Width and alignment
    std::cout << std::format("Padded: {:>8}", 42) << std::endl;
    
    return 0;
}

Output:

Pi: 3.14
Hex: 0xff
Padded:       42

🔹 Advanced Formatting

Named arguments and custom formatters provide powerful, self-documenting formatting. Instead of positional placeholders, you can use names like {name} and pass arguments as key-value pairs, improving template clarity. Additionally, defining custom formatter specializations for user-defined types allows seamless integration of complex objects into format strings. This extensibility is key for logging systems, serialization, and generating structured documents where both readability and type safety are paramount.

#include <format>
#include <iostream>

int main() {
    // Indexed arguments
    std::cout << std::format("{1} {0}!", "World", "Hello") << std::endl;
    
    // Fill and align
    std::string text = "C++";
    std::cout << std::format("{:*^10}", text) << std::endl;
    
    // Boolean formatting
    bool flag = true;
    std::cout << std::format("Flag: {}", flag) << std::endl;
    
    return 0;
}

Output:

Hello World!
***C++****
Flag: true

🧠 Test Your Knowledge

What C++ version introduced std::format?