1 .. _string-formatting-api:
7 The {fmt} library API consists of the following parts:
9 * :ref:`fmt/core.h <core-api>`: the core API providing argument handling
10 facilities and a lightweight subset of formatting functions
11 * :ref:`fmt/format.h <format-api>`: the full format API providing compile-time
12 format string checks, output iterator and user-defined type support
13 * :ref:`fmt/time.h <time-api>`: date and time formatting
14 * :ref:`fmt/ostream.h <ostream-api>`: ``std::ostream`` support
15 * :ref:`fmt/printf.h <printf-api>`: ``printf`` formatting
17 All functions and types provided by the library reside in namespace ``fmt`` and
18 macros have prefix ``FMT_`` or ``fmt``.
25 ``fmt/core.h`` defines the core API which provides argument handling facilities
26 and a lightweight subset of formatting functions.
28 The following functions use :ref:`format string syntax <syntax>`
29 similar to that of Python's `str.format
30 <http://docs.python.org/3/library/stdtypes.html#str.format>`_.
31 They take *format_str* and *args* as arguments.
33 *format_str* is a format string that contains literal text and replacement
34 fields surrounded by braces ``{}``. The fields are replaced with formatted
35 arguments in the resulting string. A function taking *format_str* doesn't
36 participate in an overload resolution if the latter is not a string.
38 *args* is an argument list representing objects to be formatted.
42 .. doxygenfunction:: format(const S&, const Args&...)
43 .. doxygenfunction:: vformat(const S&, basic_format_args<typename buffer_context<Char>::type>)
47 .. doxygenfunction:: print(const S&, const Args&...)
48 .. doxygenfunction:: vprint(string_view, format_args)
50 .. doxygenfunction:: print(std::FILE *, const S&, const Args&...)
51 .. doxygenfunction:: vprint(std::FILE *, string_view, format_args)
52 .. doxygenfunction:: vprint(std::FILE *, wstring_view, wformat_args)
57 .. doxygenfunction:: fmt::arg(string_view, const T&)
62 .. doxygenfunction:: fmt::make_format_args(const Args&...)
64 .. doxygenclass:: fmt::format_arg_store
67 .. doxygenclass:: fmt::basic_format_args
70 .. doxygenstruct:: fmt::format_args
72 .. doxygenclass:: fmt::basic_format_arg
78 .. doxygenclass:: fmt::basic_string_view
81 .. doxygentypedef:: fmt::string_view
82 .. doxygentypedef:: fmt::wstring_view
89 ``fmt/format.h`` defines the full format API providing compile-time format
90 string checks, output iterator and user-defined type support.
92 Compile-time format string checks
93 ---------------------------------
95 .. doxygendefine:: fmt
97 Formatting user-defined types
98 -----------------------------
100 To make a user-defined type formattable, specialize the ``formatter<T>`` struct
101 template and implement ``parse`` and ``format`` methods::
103 #include <fmt/format.h>
105 struct point { double x, y; };
109 struct formatter<point> {
110 template <typename ParseContext>
111 constexpr auto parse(ParseContext &ctx) { return ctx.begin(); }
113 template <typename FormatContext>
114 auto format(const point &p, FormatContext &ctx) {
115 return format_to(ctx.begin(), "({:.1f}, {:.1f})", p.x, p.y);
120 Then you can pass objects of type ``point`` to any formatting function::
123 std::string s = fmt::format("{}", p);
126 In the example above the ``formatter<point>::parse`` function ignores the
127 contents of the format string referred to by ``ctx.begin()`` so the object will
128 always be formatted in the same way. See ``formatter<tm>::parse`` in
129 :file:`fmt/time.h` for an advanced example of how to parse the format string and
130 customize the formatted output.
132 You can also reuse existing formatters, for example::
134 enum class color {red, green, blue};
137 struct fmt::formatter<color>: formatter<string_view> {
138 // parse is inherited from formatter<string_view>.
139 template <typename FormatContext>
140 auto format(color c, FormatContext &ctx) {
141 string_view name = "unknown";
143 case color::red: name = "red"; break;
144 case color::green: name = "green"; break;
145 case color::blue: name = "blue"; break;
147 return formatter<string_view>::format(name, ctx);
151 You can also write a formatter for a hierarchy of classes::
153 #include <type_traits>
154 #include <fmt/format.h>
158 virtual std::string name() const { return "A"; }
162 virtual std::string name() const { return "B"; }
165 template <typename T>
166 struct fmt::formatter<T, std::enable_if_t<std::is_base_of<A, T>::value, char>> :
167 fmt::formatter<std::string> {
168 template <typename FormatCtx>
169 auto format(const A& a, FormatCtx& ctx) {
170 return fmt::formatter<std::string>::format(a.name(), ctx);
177 fmt::print("{}", a); // prints "B"
180 This section shows how to define a custom format function for a user-defined
181 type. The next section describes how to get ``fmt`` to use a conventional stream
182 output ``operator<<`` when one is defined for a user-defined type.
184 Output iterator support
185 -----------------------
187 .. doxygenfunction:: fmt::format_to(OutputIt, const S &, const Args &...)
188 .. doxygenfunction:: fmt::format_to_n(OutputIt, std::size_t, string_view, const Args&...)
189 .. doxygenstruct:: fmt::format_to_n_result
195 The following user-defined literals are defined in ``fmt/format.h``.
197 .. doxygenfunction:: operator""_format(const char *, std::size_t)
199 .. doxygenfunction:: operator""_a(const char *, std::size_t)
204 .. doxygentypedef:: fmt::char_t
206 .. doxygenfunction:: fmt::formatted_size(string_view, const Args&...)
208 .. doxygenfunction:: fmt::to_string(const T&)
210 .. doxygenfunction:: fmt::to_wstring(const T&)
212 .. doxygenclass:: fmt::basic_memory_buffer
219 fmt does not use ``errno`` to communicate errors to the user, but it may call
220 system functions which set ``errno``. Users should not make any assumptions about
221 the value of ``errno`` being preserved by library functions.
223 .. doxygenclass:: fmt::system_error
226 .. doxygenfunction:: fmt::format_system_error
228 .. doxygenclass:: fmt::windows_error
236 The {fmt} library supports custom dynamic memory allocators.
237 A custom allocator class can be specified as a template argument to
238 :class:`fmt::basic_memory_buffer`::
240 using custom_memory_buffer =
241 fmt::basic_memory_buffer<char, fmt::inline_buffer_size, custom_allocator>;
243 It is also possible to write a formatting function that uses a custom
246 using custom_string =
247 std::basic_string<char, std::char_traits<char>, custom_allocator>;
249 custom_string vformat(custom_allocator alloc, fmt::string_view format_str,
250 fmt::format_args args) {
251 custom_memory_buffer buf(alloc);
252 fmt::vformat_to(buf, format_str, args);
253 return custom_string(buf.data(), buf.size(), alloc);
256 template <typename ...Args>
257 inline custom_string format(custom_allocator alloc,
258 fmt::string_view format_str,
259 const Args & ... args) {
260 return vformat(alloc, format_str, fmt::make_format_args(args...));
263 The allocator will be used for the output container only. If you are using named
264 arguments, the container that stores pointers to them will be allocated using
265 the default allocator. Also floating-point formatting falls back on ``sprintf``
266 which may do allocations.
268 Custom formatting of built-in types
269 -----------------------------------
271 It is possible to change the way arguments are formatted by providing a
272 custom argument formatter class::
274 using arg_formatter =
275 fmt::arg_formatter<fmt::back_insert_range<fmt::internal::buffer>>;
277 // A custom argument formatter that formats negative integers as unsigned
278 // with the ``x`` format specifier.
279 class custom_arg_formatter : public arg_formatter {
281 custom_arg_formatter(fmt::format_context &ctx,
282 fmt::format_specs *spec = nullptr)
283 : arg_formatter(ctx, spec) {}
285 using arg_formatter::operator();
287 auto operator()(int value) {
288 if (spec().type() == 'x')
289 return (*this)(static_cast<unsigned>(value)); // convert to unsigned and format
290 return arg_formatter::operator()(value);
294 std::string custom_vformat(fmt::string_view format_str, fmt::format_args args) {
295 fmt::memory_buffer buffer;
296 // Pass custom argument formatter as a template arg to vformat_to.
297 fmt::vformat_to<custom_arg_formatter>(buffer, format_str, args);
298 return fmt::to_string(buffer);
301 template <typename ...Args>
302 inline std::string custom_format(
303 fmt::string_view format_str, const Args &... args) {
304 return custom_vformat(format_str, fmt::make_format_args(args...));
307 std::string s = custom_format("{:x}", -42); // s == "ffffffd6"
309 .. doxygenclass:: fmt::arg_formatter
314 Date and time formatting
315 ========================
317 The library supports `strftime
318 <http://en.cppreference.com/w/cpp/chrono/c/strftime>`_-like date and time
321 #include <fmt/time.h>
323 std::time_t t = std::time(nullptr);
324 // Prints "The date is 2016-04-29." (with the current date)
325 fmt::print("The date is {:%Y-%m-%d}.", *std::localtime(&t));
327 The format string syntax is described in the documentation of
328 `strftime <http://en.cppreference.com/w/cpp/chrono/c/strftime>`_.
332 ``std::ostream`` support
333 ========================
335 ``fmt/ostream.h`` provides ``std::ostream`` support including formatting of
336 user-defined types that have overloaded ``operator<<``::
338 #include <fmt/ostream.h>
341 int year_, month_, day_;
343 date(int year, int month, int day): year_(year), month_(month), day_(day) {}
345 friend std::ostream &operator<<(std::ostream &os, const date &d) {
346 return os << d.year_ << '-' << d.month_ << '-' << d.day_;
350 std::string s = fmt::format("The date is {}", date(2012, 12, 9));
351 // s == "The date is 2012-12-9"
353 .. doxygenfunction:: print(std::basic_ostream<fmt::char_t<S>>&, const S&, const Args&...)
357 ``printf`` formatting
358 =====================
360 The header ``fmt/printf.h`` provides ``printf``-like formatting functionality.
361 The following functions use `printf format string syntax
362 <http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html>`_ with
363 the POSIX extension for positional arguments. Unlike their standard
364 counterparts, the ``fmt`` functions are type-safe and throw an exception if an
365 argument type doesn't match its format specification.
367 .. doxygenfunction:: printf(const S&, const Args&...)
369 .. doxygenfunction:: fprintf(std::FILE *, const S&, const Args&...)
371 .. doxygenfunction:: fprintf(std::basic_ostream<fmt::char_t<S>>&, const S&, const Args&...)
373 .. doxygenfunction:: sprintf(const S&, const Args&...)