fmt

Language: CPP

CLI/Utils

fmt was created by Victor Zverovich to provide an efficient and safe formatting library for C++ that combines the convenience of Python’s str.format with C++ type safety. It became widely used and is the basis for C++20's std::format.

fmt is a modern C++ library for safe and fast string formatting. It provides a type-safe alternative to printf and std::stringstream, supporting Python-like format strings and compile-time checks.

Installation

linux: sudo apt install libfmt-dev
mac: brew install fmt
windows: Download and build from https://github.com/fmtlib/fmt

Usage

fmt allows formatting strings using Python-like replacement fields with `{}`. It supports compile-time checking, positional arguments, named arguments, width, alignment, precision, and localization.

Basic string formatting

#include <fmt/core.h>
#include <iostream>

int main() {
    std::string name = "Alice";
    int age = 30;
    std::cout << fmt::format("{} is {} years old", name, age) << std::endl;
    return 0;
}

Formats a string using `{}` placeholders for variables.

Named arguments

#include <fmt/core.h>
#include <iostream>

int main() {
    std::cout << fmt::format("{name} is {age} years old", fmt::arg("name", "Bob"), fmt::arg("age", 25)) << std::endl;
    return 0;
}

Demonstrates using named arguments for string formatting.

Formatting numbers

#include <fmt/core.h>
#include <iostream>

int main() {
    double pi = 3.14159265;
    std::cout << fmt::format("Pi rounded to 2 decimals: {:.2f}", pi) << std::endl;
    return 0;
}

Formats a floating-point number with 2 decimal places.

Alignment and width

#include <fmt/core.h>
#include <iostream>

int main() {
    std::cout << fmt::format("|{:<10}|{:^10}|{:>10}|", "left", "center", "right") << std::endl;
    return 0;
}

Shows left, center, and right alignment within a fixed width.

Printing to file

#include <fmt/core.h>
#include <fstream>

int main() {
    std::ofstream file("output.txt");
    fmt::print(file, "Hello {}!\n", "World");
    return 0;
}

Writes a formatted string directly to a file.

Compile-time formatting

#include <fmt/compile.h>
#include <iostream>

int main() {
    std::cout << fmt::format(FMT_COMPILE("Hello {}!"), "World") << std::endl;
    return 0;
}

Demonstrates compile-time checked formatting for better performance and safety.

Error Handling

fmt::format_error: Thrown if the format string is invalid or arguments do not match placeholders. Ensure proper format specifiers and argument types.
std::out_of_range: Occurs if an argument index in the format string is out of range. Verify that placeholders match the number of provided arguments.

Best Practices

Prefer fmt::format over printf for type safety.

Use named arguments for clarity in long format strings.

Leverage compile-time formatting for performance-critical code.

Use fmt::print for simple output to console or files.

Combine fmt with logging libraries to format log messages safely.