Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::vformat — formatting with a runtime format string

std::vformat from <format> builds a string from a format string and a std::format_args argument pack. It accepts a pattern determined at runtime and reports invalid formatting for the supplied arguments through std::format_error.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <format>
std::string std::vformat(std::string_view fmt, std::format_args args);
std::wstring std::vformat(std::wstring_view fmt, std::wformat_args args);
std::string std::vformat(const std::locale& loc, std::string_view fmt, std::format_args args);
std::wstring std::vformat(const std::locale& loc, std::wstring_view fmt, std::wformat_args args);

std::vformat returns a new string rather than writing to a stream. It accepts a format string and a type-erased argument pack. The std::string_view overload returns std::string; the std::wstring_view overload uses std::wformat_args and returns std::wstring. Overloads taking std::locale support locale-specific formatting.

In C++23, std::format normally checks its format string at compile time. In contrast, std::vformat accepts a pattern available only at runtime. Invalid syntax, a missing referenced argument, or a specifier incompatible with its argument type causes std::format_error. Exceptions from formatters and allocation failures can also escape the call.

Build the pack with std::make_format_args using named variables. Do not treat it as owning all values: it can retain references to argument data. That data must remain valid until formatting finishes, and std::format_args itself does not extend the lifetime of the storage produced by std::make_format_args. Passing that storage directly into the call, as in the example, avoids destroying it too early.

In the example, {} inserts label, while {:04d} writes count in decimal with a minimum width of four characters and leading zeroes. The output is item: 0007 followed by a newline. This entry targets C++23; the supplied reference points to an evolving working draft that may contain later changes. A repository compiler flag does not establish library availability in the production environment.

Examples

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

int main() {
    std::string pattern = "{}: {:04d}";
    std::string label = "item";
    int count = 7;

    std::string result = std::vformat(
        pattern, std::make_format_args(label, count));
    std::cout << result << '\n';
}

Result

item: 0007

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources