Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::format_to: formatting through an output iterator

std::format_to writes formatted characters through an output iterator and returns the iterator past the last write.

Version: C++23

Syntax

template<class Out, class... Args>
Out std::format_to(Out out, std::format_string<Args...> fmt, Args&&... args);

template<class Out, class... Args>
Out std::format_to(Out out, std::wformat_string<Args...> fmt, Args&&... args);

template<class Out, class... Args>
Out std::format_to(Out out, const std::locale& loc,
    std::format_string<Args...> fmt, Args&&... args);

template<class Out, class... Args>
Out std::format_to(Out out, const std::locale& loc,
    std::wformat_string<Args...> fmt, Args&&... args);

std::format_to(out, fmt, args...) from <format> formats arguments like std::format, but does not create a result string: it assigns successive characters through out. The return value is the iterator immediately past the last written character. Character and wide-character forms exist, together with overloads accepting std::locale.

The example writes "2 + 3 = 5" at the beginning of a character array and subtracts the beginning from the returned iterator to obtain 9 written characters, so it prints 2 + 3 = 5|9. No null terminator is appended; the view therefore receives an explicit length. std::back_inserter is the usual destination for a growable container.

The destination iterator must accept the appropriate character type and remain writable for the complete result. A plain iterator into an undersized buffer ceases to meet the output-iterator requirements, and further writes have undefined behavior; format_to does not know its capacity. A literal format_string is checked against the arguments, formatting failures can throw std::format_error, allocation can throw std::bad_alloc, and formatter or iterator exceptions propagate. Use std::format_to_n when a write limit is required.

Examples

#include <array>
#include <format>
#include <iostream>
#include <string_view>

int main() {
    std::array<char, 32> buffer{};
    const auto end = std::format_to(buffer.begin(), "{} + {} = {}", 2, 3, 5);
    const std::string_view result(buffer.data(), end - buffer.begin());
    std::cout << result << '|' << result.size() << '\n';
}

Result

2 + 3 = 5|9

std::format_to → 2 + 3 = 5|9

Sources