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 imilar 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.
37 *args* is an argument list representing objects to be formatted.
41 .. doxygenfunction:: format(const String&, const Args&...)
42 .. doxygenfunction:: vformat(const String&, basic_format_args<typename buffer_context<Char>::type>)
46 .. doxygenfunction:: print(string_view, const Args&...)
47 .. doxygenfunction:: vprint(string_view, format_args)
49 .. doxygenfunction:: print(std::FILE *, string_view, const Args&...)
50 .. doxygenfunction:: vprint(std::FILE *, string_view, format_args)
52 .. doxygenfunction:: print(std::FILE *, wstring_view, const Args&...)
53 .. doxygenfunction:: vprint(std::FILE *, wstring_view, wformat_args)
58 .. doxygenfunction:: fmt::arg(string_view, const T&)
63 .. doxygenfunction:: fmt::make_format_args(const Args&...)
65 .. doxygenclass:: fmt::format_arg_store
68 .. doxygenclass:: fmt::basic_format_args
71 .. doxygenstruct:: fmt::format_args
73 .. doxygenclass:: fmt::basic_format_arg
79 .. doxygenclass:: fmt::basic_string_view
82 .. doxygentypedef:: fmt::string_view
83 .. doxygentypedef:: fmt::wstring_view
90 ``fmt/format.h`` defines the full format API providing compile-time format
91 string checks, output iterator and user-defined type support.
93 Compile-time format string checks
94 ---------------------------------
96 .. doxygendefine:: fmt
98 Formatting user-defined types
99 -----------------------------
101 To make a user-defined type formattable, specialize the ``formatter<T>`` struct
102 template and implement ``parse`` and ``format`` methods::
104 #include <fmt/format.h>
106 struct point { double x, y; };
110 struct formatter<point> {
111 template <typename ParseContext>
112 constexpr auto parse(ParseContext &ctx) { return ctx.begin(); }
114 template <typename FormatContext>
115 auto format(const point &p, FormatContext &ctx) {
116 return format_to(ctx.begin(), "({:.1f}, {:.1f})", p.x, p.y);
121 Then you can pass objects of type ``point`` to any formatting function::
124 std::string s = fmt::format("{}", p);
127 In the example above the ``formatter<point>::parse`` function ignores the
128 contents of the format string referred to by ``ctx.begin()`` so the object will
129 always be formatted in the same way. See ``formatter<tm>::parse`` in
130 :file:`fmt/time.h` for an advanced example of how to parse the format string and
131 customize the formatted output.
133 You can also reuse existing formatters, for example::
135 enum class color {red, green, blue};
138 struct fmt::formatter<color>: formatter<string_view> {
139 // parse is inherited from formatter<string_view>.
140 template <typename FormatContext>
141 auto format(color c, FormatContext &ctx) {
142 string_view name = "unknown";
144 case color::red: name = "red"; break;
145 case color::green: name = "green"; break;
146 case color::blue: name = "blue"; break;
148 return formatter<string_view>::format(name, ctx);
152 This section shows how to define a custom format function for a user-defined
153 type. The next section describes how to get ``fmt`` to use a conventional stream
154 output ``operator<<`` when one is defined for a user-defined type.
156 Output iterator support
157 -----------------------
159 .. doxygenfunction:: fmt::format_to(OutputIt, string_view, const Args&...)
160 .. doxygenfunction:: fmt::format_to_n(OutputIt, std::size_t, string_view, const Args&...)
161 .. doxygenstruct:: fmt::format_to_n_result
167 The following user-defined literals are defined in ``fmt/format.h``.
169 .. doxygenfunction:: operator""_format(const char *, std::size_t)
171 .. doxygenfunction:: operator""_a(const char *, std::size_t)
176 .. doxygenfunction:: fmt::formatted_size(string_view, const Args&...)
178 .. doxygenfunction:: fmt::to_string(const T&)
180 .. doxygenfunction:: fmt::to_wstring(const T&)
182 .. doxygenclass:: fmt::basic_memory_buffer
189 fmt does not use ``errno`` to communicate errors to the user, but it may call
190 system functions which set ``errno``. Users should not make any assumptions about
191 the value of ``errno`` being preserved by library functions.
193 .. doxygenclass:: fmt::system_error
196 .. doxygenfunction:: fmt::format_system_error
198 .. doxygenclass:: fmt::windows_error
206 The {fmt} library supports custom dynamic memory allocators.
207 A custom allocator class can be specified as a template argument to
208 :class:`fmt::basic_memory_buffer`::
210 using custom_memory_buffer =
211 fmt::basic_memory_buffer<char, fmt::inline_buffer_size, custom_allocator>;
213 It is also possible to write a formatting function that uses a custom
216 using custom_string =
217 std::basic_string<char, std::char_traits<char>, custom_allocator>;
219 custom_string vformat(custom_allocator alloc, fmt::string_view format_str,
220 fmt::format_args args) {
221 custom_memory_buffer buf(alloc);
222 fmt::vformat_to(buf, format_str, args);
223 return custom_string(buf.data(), buf.size(), alloc);
226 template <typename ...Args>
227 inline custom_string format(custom_allocator alloc,
228 fmt::string_view format_str,
229 const Args & ... args) {
230 return vformat(alloc, format_str, fmt::make_format_args(args...));
233 The allocator will be used for the output container only. If you are using named
234 arguments, the container that stores pointers to them will be allocated using
235 the default allocator. Also floating-point formatting falls back on ``sprintf``
236 which may do allocations.
238 Custom formatting of built-in types
239 -----------------------------------
241 It is possible to change the way arguments are formatted by providing a
242 custom argument formatter class::
244 using arg_formatter =
245 fmt::arg_formatter<fmt::back_insert_range<fmt::internal::buffer>>;
247 // A custom argument formatter that formats negative integers as unsigned
248 // with the ``x`` format specifier.
249 class custom_arg_formatter : public arg_formatter {
251 custom_arg_formatter(fmt::format_context &ctx, fmt::format_specs &spec)
252 : arg_formatter(ctx, spec) {}
254 using arg_formatter::operator();
256 auto operator()(int value) {
257 if (spec().type() == 'x')
258 return (*this)(static_cast<unsigned>(value)); // convert to unsigned and format
259 return arg_formatter::operator()(value);
263 std::string custom_vformat(fmt::string_view format_str, fmt::format_args args) {
264 fmt::memory_buffer buffer;
265 // Pass custom argument formatter as a template arg to vformat_to.
266 fmt::vformat_to<custom_arg_formatter>(buffer, format_str, args);
267 return fmt::to_string(buffer);
270 template <typename ...Args>
271 inline std::string custom_format(
272 fmt::string_view format_str, const Args &... args) {
273 return custom_vformat(format_str, fmt::make_format_args(args...));
276 std::string s = custom_format("{:x}", -42); // s == "ffffffd6"
278 .. doxygenclass:: fmt::arg_formatter
283 Date and time formatting
284 ========================
286 The library supports `strftime
287 <http://en.cppreference.com/w/cpp/chrono/c/strftime>`_-like date and time
290 #include <fmt/time.h>
292 std::time_t t = std::time(nullptr);
293 // Prints "The date is 2016-04-29." (with the current date)
294 fmt::print("The date is {:%Y-%m-%d}.", *std::localtime(&t));
296 The format string syntax is described in the documentation of
297 `strftime <http://en.cppreference.com/w/cpp/chrono/c/strftime>`_.
301 ``std::ostream`` support
302 ========================
304 ``fmt/ostream.h`` provides ``std::ostream`` support including formatting of
305 user-defined types that have overloaded ``operator<<``::
307 #include <fmt/ostream.h>
310 int year_, month_, day_;
312 date(int year, int month, int day): year_(year), month_(month), day_(day) {}
314 friend std::ostream &operator<<(std::ostream &os, const date &d) {
315 return os << d.year_ << '-' << d.month_ << '-' << d.day_;
319 std::string s = fmt::format("The date is {}", date(2012, 12, 9));
320 // s == "The date is 2012-12-9"
322 .. doxygenfunction:: print(std::ostream&, string_view, const Args&...)
326 ``printf`` formatting
327 =====================
329 The header ``fmt/printf.h`` provides ``printf``-like formatting functionality.
330 The following functions use `printf format string syntax
331 <http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html>`_ with
332 the POSIX extension for positional arguments. Unlike their standard
333 counterparts, the ``fmt`` functions are type-safe and throw an exception if an
334 argument type doesn't match its format specification.
336 .. doxygenfunction:: printf(string_view, const Args&...)
338 .. doxygenfunction:: fprintf(std::FILE *, string_view, const Args&...)
340 .. doxygenfunction:: fprintf(std::ostream&, string_view, const Args&...)
342 .. doxygenfunction:: sprintf(string_view, const Args&...)