All Recipes
Home/Formatting/std::format Basics
📝beginner

std::format Basics

Type-safe string formatting with std::format

Example Code

cpp
#include <format>
#include <iostream>
#include <string>
int main() {
// Basic formatting
std::string greeting = std::format("Hello, {}!", "World");
std::cout << greeting << std::endl; // Hello, World!
// Multiple arguments
std::string info = std::format("{} is {} years old", "Alice", 30);
std::cout << info << std::endl; // Alice is 30 years old
// Positional arguments
std::string reordered = std::format("{1} comes before {0}", "B", "A");
std::cout << reordered << std::endl; // A comes before B
// Numeric formatting
double pi = 3.14159265359;
std::cout << std::format("Pi: {:.2f}", pi) << std::endl; // Pi: 3.14
std::cout << std::format("Pi: {:10.4f}", pi) << std::endl; // Pi: 3.1416
// Integer formatting
int num = 255;
std::cout << std::format("Decimal: {}", num) << std::endl; // 255
std::cout << std::format("Hex: {:x}", num) << std::endl; // ff
std::cout << std::format("Hex: {:#x}", num) << std::endl; // 0xff
std::cout << std::format("Binary: {:b}", num) << std::endl; // 11111111
return 0;
}

Explanation

std::format provides Python-style string formatting with type safety. It's faster and safer than printf and more readable than iostream operators.

Key Points

  • 1{} is a placeholder for arguments
  • 2Positional arguments: {0}, {1}, etc.
  • 3Format specifiers: {:.2f}, {:x}, etc.
  • 4Type-safe at compile time