Learning Hub Search Ctrl K

Modern C++ › C++20

std::format and std::span

Type-safe formatting and non-owning array views.

Since C++20 beginner #format#span#formatting#string-formatting#views#contiguous

Explanation

std::format (<format>) is a type-safe, extensible, fast replacement for printf and stream manipulators. It uses Python-style replacement fields:

{[index][:[fill][align][sign][#][0][width][.precision][type]]}
Spec Meaning Example → result
{} default format("{}", 42) → 42
{:>8} / {:<8} / {:^8} right / left / center in width 8 [ 42]
{:08.3f} zero-padded, 3 decimals 0003.142
{:x} {:#x} {:b} hex, 0x hex, binary ff, 0xff, 11111111
{0} {1} {0} positional arguments reuse values
{:*^11} custom fill char ***hello***

The format string is checked at compile time (in std::format), so a mismatched type or placeholder count is a compile error, not a crash. std::format_to writes to an iterator, std::formatted_size returns the length, and you can specialize std::formatter<T> for your own types.

std::span<T> (<span>) is a non-owning view of a contiguous sequence (array, vector, std::array, C array), holding just a pointer and size: the array equivalent of string_view. span<const T> is a read-only view; span<T, N> has a compile-time extent. Slice with first(n), last(n), subspan(off, n).

Example

#include <array>
#include <format>
#include <iostream>
#include <numeric>
#include <span>
#include <string>
#include <vector>

double average(std::span<const double> values) {             // accepts vector, array, C array
    if (values.empty()) return 0;
    return std::accumulate(values.begin(), values.end(), 0.0) / values.size();
}

void zeroOut(std::span<int> s) { for (int& x : s) x = 0; }    // can modify through the span

struct Point { int x, y; };
template <>
struct std::formatter<Point> : std::formatter<std::string> {  // teach format about Point
    auto format(const Point& p, std::format_context& ctx) const {
        return std::formatter<std::string>::format(std::format("({}, {})", p.x, p.y), ctx);
    }
};

int main() {
    std::cout << std::format("{} scored {:.1f}% ({:#x})\n", "Ann", 93.456, 255);
    std::cout << std::format("[{:>6}] [{:<6}] [{:^6}] [{:*^7}]\n", 42, 42, 42, "hi");
    std::cout << std::format("{0} + {0} = {1}\n", 21, 42);
    std::cout << std::format("{:08.3f} {:b} {}\n", 3.14159, 10, true);
    std::cout << std::format("point: {}\n", Point{3, 4});

    std::vector<double> v{1.0, 2.0, 3.0, 4.0};
    std::array<double, 3> a{2.0, 4.0, 6.0};
    double c[] = {10.0, 20.0};
    std::cout << average(v) << " " << average(a) << " " << average(c) << "\n";   // 2.5 4 15

    std::vector<int> nums{1, 2, 3, 4, 5, 6};
    std::span<int> all(nums);
    zeroOut(all.subspan(2, 2));                                // zeroes nums[2] and nums[3]
    for (int x : nums) std::cout << x << " ";                  // 1 2 0 0 5 6
    std::cout << "\n" << all.first(2).size() << all.last(1)[0] << "\n";   // 26
    return 0;
}

Common pitfalls

  • std::format result is a std::string; building many small strings in a hot loop allocates. Use std::format_to.
  • A span does not extend lifetimes: pushing to the vector it views may reallocate and leave the span dangling.
  • span requires contiguous storage: it won’t accept std::list or deque.
  • An argument/placeholder mismatch is a compile error with std::format but a run-time exception with std::vformat.
  • Mixing signed/unsigned index types with span::size() (unsigned) gives the usual warnings.
  • Use {{ and }} to print literal braces.
  • Compiler support: MSVC 19.29+, GCC 13+, Clang 17+ (with libc++).

Legacy vs modern

// C++98: printf is unsafe; streams are verbose and stateful
printf("%s scored %.1f%%\n", name.c_str(), pct);          // wrong specifier = UB
std::cout << name << " scored " << std::fixed << std::setprecision(1) << pct << "%\n";
// C++20
std::cout << std::format("{} scored {:.1f}%\n", name, pct);

For arrays the old signature void f(const double* p, std::size_t n) loses the link between pointer and size; span carries both. See Streams and Formatting and Arrays and C Strings. C++23’s std::print writes formatted text directly.

Exercises

1. Format 7 as a width-5, zero-padded string.

std::format("{:05}", 7) gives 00007.