# API Reference — fmt 3.0.0 documentation
Small, safe and fast formatting library
Author: Victor Zverovich
Keywords: C++, formatting, printf, string, library

# API Reference

All functions and classes provided by the fmt library reside in namespace `fmt` and macros have prefix `FMT_`. For brevity the namespace is usually omitted in examples.

## Format API

The following functions use format string syntax similar to the one used by Python’s str.format function. They take format_str and args as arguments.

format_str is a format string that contains literal text and replacement fields surrounded by braces `{}`. The fields are replaced with formatted arguments in the resulting string.

args is an argument list representing arbitrary arguments.

std::string `fmt::``format`(CStringRef format_str, ArgList args)

  Formats arguments and returns the result as a string.

  Example:

      std::string message = format("The answer is {}", 42);

internal::UdlFormat<char> `fmt::literals::``operator""_format`(const char *s, std::size_t)

  C++11 literal equivalent of `fmt::format()`.

  Example:

      using namespace fmt::literals;
      std::string message = "The answer is {}"_format(42);

void `fmt::``print`(CStringRef format_str, ArgList args)

  Prints formatted data to `stdout`.

  Example:

      print("Elapsed time: {0:.2f} seconds", 1.23);

void `fmt::``print`(std::FILE *f, CStringRef format_str, ArgList args)

  Prints formatted data to the file f.

  Example:

      print(stderr, "Don't {}!", "panic");

template <typename CharType, typename ArgFormatter>
class `fmt::``BasicFormatter`

  This template formats data and writes the output to a writer.

  Public Types

  typedef CharType `Char`

    The character type for the output.

  Public Functions

  `BasicFormatter`(const ArgList &args, BasicWriter<Char> &w)

    Constructs a `BasicFormatter` object. References to the arguments and the writer are stored in the formatter object so make sure they have appropriate lifetimes.

  BasicWriter<Char> &`writer`()

    Returns a reference to the writer associated with this formatter.

  void `format`( BasicCStringRef<Char> format_str)

    Formats stored arguments and writes the output to the writer.

### Date and time formatting

The library supports strftime-like date and time formatting:

    #include "fmt/time.h"

    std::time_t t = std::time(nullptr);
    // Prints "The date is 2016-04-29." (with the current date)
    fmt::print("The date is {:%Y-%m-%d}.", *std::localtime(&t));

The format string syntax is described in the documentation of strftime.

### `std::ostream` support

The header `fmt/ostream.h` provides `std::ostream` support including formatting of user-defined types that have overloaded `operator<<`:

    #include "fmt/ostream.h"

    class Date {
      int year_, month_, day_;
    public:
      Date(int year, int month, int day) : year_(year), month_(month), day_(day) {}

      friend std::ostream &operator<<(std::ostream &os, const Date &d) {
        return os << d.year_ << '-' << d.month_ << '-' << d.day_;
      }
    };

    std::string s = fmt::format("The date is {}", Date(2012, 12, 9));
    // s == "The date is 2012-12-9"

void `fmt::``print`(std::ostream &os, CStringRef format_str, ArgList args)

  Prints formatted data to the stream os.

  Example:

      print(cerr, "Don't {}!", "panic");

int `fmt::``fprintf`(std::ostream &os, CStringRef format_str, ArgList args)

  Prints formatted data to the stream os.

  Example:

      fprintf(cerr, "Don't %s!", "panic");

### Argument formatters

It is possible to change the way arguments are formatted by providing a custom argument formatter class:

    // A custom argument formatter that formats negative integers as unsigned
    // with the ``x`` format specifier.
    class CustomArgFormatter :
      public fmt::BasicArgFormatter<CustomArgFormatter, char>  {
      public:
      CustomArgFormatter(fmt::BasicFormatter<char, CustomArgFormatter> &f,
                         fmt::FormatSpec &s, const char *fmt)
        : fmt::BasicArgFormatter<CustomArgFormatter, char>(f, s, fmt) {}

      void visit_int(int value) {
        if (spec().type() == 'x')
          visit_uint(value); // convert to unsigned and format
        else
          fmt::BasicArgFormatter<CustomArgFormatter, char>::visit_int(value);
      }
    };

    std::string custom_format(const char *format_str, fmt::ArgList args) {
      fmt::MemoryWriter writer;
      // Pass custom argument formatter as a template arg to BasicFormatter.
      fmt::BasicFormatter<char, CustomArgFormatter> formatter(args, writer);
      formatter.format(format_str);
      return writer.str();
    }
    FMT_VARIADIC(std::string, custom_format, const char *)

    std::string s = custom_format("{:x}", -42); // s == "ffffffd6"

template <typename Impl, typename Result>
class `fmt::``ArgVisitor`

  An argument visitor based on the curiously recurring template pattern.

  To use `ArgVisitor` define a subclass that implements some or all of the visit methods with the same signatures as the methods in `ArgVisitor`, for example, `visit_int()`. Pass the subclass as the Impl template parameter. Then calling `visit()` for some argument will dispatch to a visit method specific to the argument type. For example, if the argument type is `double` then the `visit_double()` method of a subclass will be called. If the subclass doesn’t contain a method with this signature, then a corresponding method of `ArgVisitor` will be called.

  Example:

      class MyArgVisitor : public fmt::ArgVisitor<MyArgVisitor, void> {
       public:
        void visit_int(int value) { fmt::print("{}", value); }
        void visit_double(double value) { fmt::print("{}", value ); }
      };

  Public Functions

  Result `visit_int`(int value)

    Visits an `int` argument.

  Result `visit_long_long`(LongLong value)

    Visits a `long long` argument.

  Result `visit_uint`(unsigned value)

    Visits an `unsigned` argument.

  Result `visit_ulong_long`(ULongLong value)

    Visits an `unsigned long long` argument.

  Result `visit_bool`(bool value)

    Visits a `bool` argument.

  Result `visit_char`(int value)

    Visits a `char` or `wchar_t` argument.

  template <typename T>
  Result `visit_any_int`(T)

    Visits an argument of any integral type.

  Result `visit_double`(double value)

    Visits a `double` argument.

  Result `visit_long_double`(long double value)

    Visits a `long double` argument.

  template <typename T>
  Result `visit_any_double`(T)

    Visits a `double` or `long double` argument.

  Result `visit_cstring`(const char *)

    Visits a null-terminated C string (`const char *`) argument.

  Result `visit_string`(Arg::StringValue<char>)

    Visits a string argument.

  Result `visit_wstring`(Arg::StringValue<wchar_t>)

    Visits a wide string argument.

  Result `visit_pointer`(const void *)

    Visits a pointer argument.

  Result `visit_custom`(Arg::CustomValue)

    Visits an argument of a custom (user-defined) type.

  Result `visit`(const Arg &arg)

    Visits an argument dispatching to the appropriate visit method based on the argument type. For example, if the argument type is `double` then the `visit_double()` method of the Impl class will be called.

template <typename Impl, typename Char>
class `fmt::``BasicArgFormatter`

  An argument formatter based on the curiously recurring template pattern.

  To use `BasicArgFormatter` define a subclass that implements some or all of the visit methods with the same signatures as the methods in `ArgVisitor`, for example, `visit_int()`. Pass the subclass as the Impl template parameter. When a formatting function processes an argument, it will dispatch to a visit method specific to the argument type. For example, if the argument type is `double` then the `visit_double()` method of a subclass will be called. If the subclass doesn’t contain a method with this signature, then a corresponding method of `BasicArgFormatter` or its superclass will be called.

  Public Functions

  `BasicArgFormatter`( BasicFormatter<Char, Impl> &formatter, FormatSpec &spec, const Char *fmt)

    Constructs an argument formatter object. formatter is a reference to the main formatter object, spec contains format specifier information for standard argument types, and fmt points to the part of the format string being parsed for custom argument types.

  void `visit_custom`(internal::Arg::CustomValue c)

    Formats argument of a custom (user-defined) type.

template <typename Char>
class `fmt::``ArgFormatter`

  The default argument formatter.

  Public Functions

  `ArgFormatter`( BasicFormatter<Char> &formatter, FormatSpec &spec, const Char *fmt)

    Constructs an argument formatter object.

### Printf formatting functions

The following functions use printf format string syntax with a POSIX extension for positional arguments.

int `fmt::``printf`(CStringRef format, ArgList args)

  Prints formatted data to `stdout`.

  Example:

      fmt::printf("Elapsed time: %.2f seconds", 1.23);

int `fmt::``fprintf`(std::FILE *f, CStringRef format, ArgList args)

  Prints formatted data to the file f.

  Example:

      fmt::fprintf(stderr, "Don't %s!", "panic");

std::string `fmt::``sprintf`(CStringRef format, ArgList args)

  Formats arguments and returns the result as a string.

  Example:

      std::string message = fmt::sprintf("The answer is %d", 42);

## Write API

template <typename Char>
class `fmt::``BasicWriter`

  This template provides operations for formatting and writing data into a character stream. The output is stored in a buffer provided by a subclass such as `fmt::BasicMemoryWriter`.

  You can use one of the following typedefs for common character types:

  Type | Definition
  --- | ---
  Writer | BasicWriter<char>
  WWriter | BasicWriter<wchar_t>

  Public Functions

  virtual `~BasicWriter`()

    Destroys a `BasicWriter` object.

  std::size_t `size`() const

    Returns the total number of characters written.

  const Char *`data`() const

    Returns a pointer to the output buffer content.

    No terminating null character is appended.

  const Char *`c_str`() const

    Returns a pointer to the output buffer content with terminating null character appended.

  std::basic_string<Char> `str`() const

    Returns the content of the output buffer as an `std::string`.

  void `write`( BasicCStringRef<Char> format, ArgList args)

    Writes formatted data.

    args is an argument list representing arbitrary arguments.

    Example:

        MemoryWriter out;
        out.write("Current point:\n");
        out.write("({:+f}, {:+f})", -3.14, 3.14);

    This will write the following output to the `out` object:

        Current point:
        (-3.140000, +3.140000)

    The output can be accessed using `data()`, `c_str()` or `str()` methods.

    See also Format String Syntax.

  BasicWriter &`operator<<`(ULongLong value)

    Formats value and writes it to the stream.

  BasicWriter &`operator<<`(long double value)

    Formats value using the general format for floating-point numbers (`'g'`) and writes it to the stream.

  BasicWriter &`operator<<`(char value)

    Writes a character to the stream.

  BasicWriter &`operator<<`(fmt::BasicStringRef<Char> value)

    Writes value to the stream.

template <typename Char, typename Allocator = std::allocator<Char>>
class `fmt::``BasicMemoryWriter`

  This class template provides operations for formatting and writing data into a character stream. The output is stored in a memory buffer that grows dynamically.

  You can use one of the following typedefs for common character types and the standard allocator:

  Type | Definition
  --- | ---
  MemoryWriter | BasicMemoryWriter<char, std::allocator<char>>
  WMemoryWriter | BasicMemoryWriter<wchar_t, std::allocator<wchar_t>>

  Example:

      MemoryWriter out;
      out << "The answer is " << 42 << "\n";
      out.write("({:+f}, {:+f})", -3.14, 3.14);

  This will write the following output to the `out` object:

      The answer is 42
      (-3.140000, +3.140000)

  The output can be converted to an `std::string` with `out.str()` or accessed as a C string with `out.c_str()`.

  Public Functions

  `BasicMemoryWriter`( BasicMemoryWriter &&other)

    Constructs a `fmt::BasicMemoryWriter` object moving the content of the other object to it.

  BasicMemoryWriter &`operator=`( BasicMemoryWriter &&other)

    Moves the content of the other `BasicMemoryWriter` object to this one.

template <typename Char>
class `fmt::``BasicArrayWriter`

  This class template provides operations for formatting and writing data into a fixed-size array. For writing into a dynamically growing buffer use `fmt::BasicMemoryWriter`.

  Any write method will throw `std::runtime_error` if the output doesn’t fit into the array.

  You can use one of the following typedefs for common character types:

  Type | Definition
  --- | ---
  ArrayWriter | BasicArrayWriter<char>
  WArrayWriter | BasicArrayWriter<wchar_t>

  Public Functions

  `BasicArrayWriter`(Char *array, std::size_t size)

    Constructs a `fmt::BasicArrayWriter` object for array of the given size.

  template <std::size_t SIZE>
  `BasicArrayWriter`(Char (&array)[SIZE])

    Constructs a `fmt::BasicArrayWriter` object for array of the size known at compile time.

IntFormatSpec<int, TypeSpec<'b'>> `fmt::``bin`(int value)

  Returns an integer format specifier to format the value in base 2.

IntFormatSpec<int, TypeSpec<'o'>> `fmt::``oct`(int value)

  Returns an integer format specifier to format the value in base 8.

IntFormatSpec<int, TypeSpec<'x'>> `fmt::``hex`(int value)

  Returns an integer format specifier to format the value in base 16 using lower-case letters for the digits above 9.

IntFormatSpec<int, TypeSpec<'X'>> `fmt::``hexu`(int value)

  Returns an integer formatter format specifier to format in base 16 using upper-case letters for the digits above 9.

template <char TYPE_CODE, typename Char>
IntFormatSpec<int, AlignTypeSpec<TYPE_CODE>, Char> `fmt::``pad`(int value, unsigned width, Char fill)

  Returns an integer format specifier to pad the formatted argument with the fill character to the specified width using the default (right) numeric alignment.

  Example:

      MemoryWriter out;
      out << pad(hex(0xcafe), 8, '0');
      // out.str() == "0000cafe"

## Utilities

template <typename T>
internal::NamedArg<char> `fmt::``arg`(StringRef name, const T &arg)

  Returns a named argument for formatting functions.

  Example:

      print("Elapsed time: {s:.2f} seconds", arg("s", 1.23));

internal::UdlArg<char> `fmt::literals::``operator""_a`(const char *s, std::size_t)

  C++11 literal equivalent of `fmt::arg()`.

  Example:

      using namespace fmt::literals;
      print("Elapsed time: {s:.2f} seconds", "s"_a=1.23);

`FMT_CAPTURE`(...)

  Convenient macro to capture the arguments’ names and values into several `fmt::arg(name, value)`.

  Example:

      int x = 1, y = 2;
      print("point: ({x}, {y})", FMT_CAPTURE(x, y));
      // same as:
      // print("point: ({x}, {y})", arg("x", x), arg("y", y));

`FMT_VARIADIC`(ReturnType, func, ...)

  Defines a variadic function with the specified return type, function name and argument types passed as variable arguments to this macro.

  Example:

      void print_error(const char *file, int line, const char *format,
                       fmt::ArgList args) {
        fmt::print("{}: {}: ", file, line);
        fmt::print(format, args);
      }
      FMT_VARIADIC(void, print_error, const char *, int, const char *)

  `FMT_VARIADIC` is used for compatibility with legacy C++ compilers that don’t implement variadic templates. You don’t have to use this macro if you don’t need legacy compiler support and can use variadic templates directly:

      template <typename... Args>
      void print_error(const char *file, int line, const char *format,
                       const Args & ... args) {
        fmt::print("{}: {}: ", file, line);
        fmt::print(format, args...);
      }

class `fmt::``ArgList`

  An argument list.

  Public Functions

  internal::Arg `operator[]`(unsigned index) const

    Returns the argument at specified index.

template <typename Char>
class `fmt::``BasicStringRef`

  A string reference. It can be constructed from a C string or `std::string`.

  You can use one of the following typedefs for common character types:

  Type | Definition
  --- | ---
  StringRef | BasicStringRef<char>
  WStringRef | BasicStringRef<wchar_t>

  This class is most useful as a parameter type to allow passing different types of strings to a function, for example:

      template <typename... Args>
      std::string format(StringRef format_str, const Args & ... args);

      format("{}", 42);
      format(std::string("{}"), 42);

  Public Functions

  `BasicStringRef`(const Char *s, std::size_t size)

    Constructs a string reference object from a C string and a size.

  `BasicStringRef`(const Char *s)

    Constructs a string reference object from a C string computing the size with `std::char_traits<Char>::length`.

  `BasicStringRef`(const std::basic_string<Char> &s)

    Constructs a string reference from an `std::string` object.

  std::basic_string<Char> `to_string`() const

    Converts a string reference to an `std::string` object.

  const Char *`data`() const

    Returns a pointer to the string data.

  std::size_t `size`() const

    Returns the string size.

template <typename Char>
class `fmt::``BasicCStringRef`

  A reference to a null terminated string. It can be constructed from a C string or `std::string`.

  You can use one of the following typedefs for common character types:

  Type | Definition
  --- | ---
  CStringRef | BasicCStringRef<char>
  WCStringRef | BasicCStringRef<wchar_t>

  This class is most useful as a parameter type to allow passing different types of strings to a function, for example:

      template <typename... Args>
      std::string format(CStringRef format_str, const Args & ... args);

      format("{}", 42);
      format(std::string("{}"), 42);

  Public Functions

  `BasicCStringRef`(const Char *s)

    Constructs a string reference object from a C string.

  `BasicCStringRef`(const std::basic_string<Char> &s)

    Constructs a string reference from an `std::string` object.

  const Char *`c_str`() const

    Returns the pointer to a C string.

template <typename T>
class `fmt::``Buffer`

  A buffer supporting a subset of `std::vector`‘s operations.

  Public Functions

  std::size_t `size`() const

    Returns the size of this buffer.

  std::size_t `capacity`() const

    Returns the capacity of this buffer.

  void `resize`(std::size_t new_size)

    Resizes the buffer.

    If T is a POD type new elements may not be initialized.

  void `reserve`(std::size_t capacity)

    Reserves space to store at least capacity elements.

  template <typename U>
  void `append`(const U *begin, const U *end)

    Appends data to the end of the buffer.

  Protected Functions

  virtual void `grow`(std::size_t size) = 0

    Increases the buffer capacity to hold at least size elements updating `ptr_` and `capacity_`.

## System errors

class `fmt::``SystemError`

  An error returned by an operating system or a language runtime, for example a file opening error.

  Public Functions

  `SystemError`(int error_code, CStringRef message)

    Constructs a `fmt::SystemError` object with the description of the form

        <message>: <system-message>

    where <message> is the formatted message and <system-message> is the system message corresponding to the error code. error_code is a system error code as given by `errno`. If error_code is not a valid error code such as -1, the system message may look like “Unknown error -1” and is platform-dependent.

    Example:

        // This throws a SystemError with the description
        //   cannot open file 'madeup': No such file or directory
        // or similar (system message may vary).
        const char *filename = "madeup";
        std::FILE *file = std::fopen(filename, "r");
        if (!file)
          throw fmt::SystemError(errno, "cannot open file '{}'", filename);

class `fmt::``WindowsError`

  A Windows error.

  Public Functions

  `WindowsError`(int error_code, CStringRef message)

    Constructs a `fmt::WindowsError` object with the description of the form

        <message>: <system-message>

    where <message> is the formatted message and <system-message> is the system message corresponding to the error code. error_code is a Windows error code as given by `GetLastError`. If error_code is not a valid error code such as -1, the system message will look like “error -1”.

    Example:

        // This throws a WindowsError with the description
        //   cannot open file 'madeup': The system cannot find the file specified.
        // or similar (system message may vary).
        const char *filename = "madeup";
        LPOFSTRUCT of = LPOFSTRUCT();
        HFILE file = OpenFile(filename, &of, OF_READ);
        if (file == HFILE_ERROR) {
          throw fmt::WindowsError(GetLastError(),
                                  "cannot open file '{}'", filename);
        }

## Custom allocators

The fmt library supports custom dynamic memory allocators. A custom allocator class can be specified as a template argument to `fmt::BasicMemoryWriter`:

    typedef fmt::BasicMemoryWriter<char, CustomAllocator> CustomMemoryWriter;

It is also possible to write a formatting function that uses a custom allocator:

    typedef std::basic_string<char, std::char_traits<char>, CustomAllocator> CustomString;

    CustomString format(CustomAllocator alloc, fmt::CStringRef format_str,
                        fmt::ArgList args) {
      CustomMemoryWriter writer(alloc);
      writer.write(format_str, args);
      return CustomString(writer.data(), writer.size(), alloc);
    }
    FMT_VARIADIC(CustomString, format, CustomAllocator, fmt::CStringRef)