CKTIS / C++
std::format: typed formatting into a new string
std::format creates a new std::string from a checked format pattern and its arguments.
Version: C++23
Syntax
template<class... Args>
std::string std::format(std::format_string<Args...> fmt, Args&&... args);
template<class... Args>
std::wstring std::format(std::wformat_string<Args...> fmt, Args&&... args);
template<class... Args>
std::string std::format(const std::locale& loc,
std::format_string<Args...> fmt, Args&&... args);
template<class... Args>
std::wstring std::format(const std::locale& loc,
std::wformat_string<Args...> fmt, Args&&... args);std::format(fmt, args...) from <format> returns a new std::string containing argument representations placed into replacement fields; the wide-character counterpart returns std::wstring, and separate overloads accept std::locale. In C++23 an ordinary call uses format_string<Args...>, whose literal is checked at compile time against argument count and types.
The example formats 7 as four digits 0007, formats 3.5 with two fractional digits, and turns doubled braces into literal text, printing 0007 3.50 {ok}. {} selects the next argument, while the part after : controls properties such as alignment, width, precision, and presentation type. std::format returns a separate string; std::format_to writes through an output iterator.
Write literal braces as {{ and }}; automatic {} and manual {0} argument numbering must not be mixed. An invalid literal or type-incompatible specification normally makes the call ill-formed during compilation. For a pattern known only at run time, use std::vformat. std::format itself can also throw std::format_error for a value-dependent failure detected at run time, such as an invalid dynamic width or precision; exceptions from formatter operations propagate, and allocation can throw std::bad_alloc. A user-defined type needs a valid std::formatter specialization, and locale-specific formatting uses the std::locale overload plus appropriate format options.
Examples
#include <format>
#include <iostream>
int main() {
std::cout << std::format("{:04} {:.2f} {{ok}}", 7, 3.5) << '\n';
}
Result
0007 3.50 {ok}std::format → 0007 3.50 {ok}