API Reference

The {fmt} library API consists of the following parts:

  • fmt/core.h: the core API providing argument handling facilities and a lightweight subset of formatting functions
  • fmt/format.h: the full format API providing compile-time format string checks, wide string, output iterator and user-defined type support
  • fmt/ranges.h: additional formatting support for ranges and tuples
  • fmt/chrono.h: date and time formatting
  • fmt/compile.h: format string compilation
  • fmt/color.h: terminal color and text style
  • fmt/ostream.h: std::ostream support
  • fmt/printf.h: printf formatting

All functions and types provided by the library reside in namespace fmt and macros have prefix FMT_.

Core API

fmt/core.h defines the core API which provides argument handling facilities and a lightweight subset of formatting functions. In the header-only mode include fmt/format.h instead of fmt/core.h.

The following functions use format string syntax similar to that of Python’s str.format. 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. A function taking format_str doesn’t participate in an overload resolution if the latter is not a string.

args is an argument list representing objects to be formatted.

template <typename S, typename... Args, typename Char = char_t<S>>
std::basic_string<Char> fmt::format(const S &format_str, Args&&... args)

Formats arguments and returns the result as a string.

Example:

#include <fmt/core.h>
std::string message = fmt::format("The answer is {}", 42);

template <typename S, typename Char = char_t<S>>
std::basic_string<Char> fmt::vformat(const S &format_str, basic_format_args<buffer_context<type_identity_t<Char>>> args)

Warning

doxygenfunction: Unable to resolve multiple matches for function “fmt::format_to” with arguments (OutputIt, string_view, Args&&...) in doxygen xml output for project “format” from directory: /home/travis/build/fmtlib/fmt/doxyxml. Potential matches:

- template <typename OutputIt, typename CompiledFormat, typename... *Args*, CompiledFormat>
  ::value OutputIt fmt::format_to(OutputIt, const CompiledFormat &, const Args &...)
- template <typename OutputIt, typename S, typename... *Args*>
  OutputIt fmt::format_to(OutputIt, const S&, Args&&...)
- template <typename OutputIt, typename S, typename... *Args*>
  OutputIt fmt::format_to(OutputIt, const S&, const Args&...)
- template <typename S, typename... *Args*, size_t *SIZE* = inline_buffer_size, typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
  buffer_context<Char>::iterator fmt::format_to(basic_memory_buffer<Char, SIZE>&, const S&, Args&&...)

Warning

doxygenfunction: Unable to resolve multiple matches for function “fmt::format_to_n” with arguments (OutputIt, size_t, string_view, Args&&...) in doxygen xml output for project “format” from directory: /home/travis/build/fmtlib/fmt/doxyxml. Potential matches:

- template <typename OutputIt, typename CompiledFormat, typename... *Args*, CompiledFormat>
  ::value format_to_n_result<OutputIt> fmt::format_to_n(OutputIt, size_t, const CompiledFormat &, const Args &...)
- template <typename OutputIt, typename S, typename... *Args*>
  format_to_n_result<OutputIt> fmt::format_to_n(OutputIt, size_t, const S&, const Args&...)
template <typename... Args>
size_t fmt::formatted_size(string_view format_str, Args&&... args)

Returns the number of characters in the output of format(format_str, args...).

template <typename S, typename... Args, typename Char = char_t<S>>
void fmt::print(const S &format_str, Args&&... args)

Formats args according to specifications in format_str and writes the output to stdout. Strings are assumed to be Unicode-encoded unless the FMT_UNICODE macro is set to 0.

Example:

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

void fmt::buffered_file::vprint(string_view format_str, format_args args)
template <typename S, typename... Args, typename Char = char_t<S>>
void fmt::print(std::FILE *f, const S &format_str, Args&&... args)

Formats args according to specifications in format_str and writes the output to the file f. Strings are assumed to be Unicode-encoded unless the FMT_UNICODE macro is set to 0.

Example:

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

void fmt::vprint(std::FILE *, string_view, format_args)

Named Arguments

template <typename Char, typename T>
detail::named_arg<Char, T> fmt::arg(const Char *name, const T &arg)

Returns a named argument to be used in a formatting function. It should only be used in a call to a formatting function.

Example:

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

Named arguments are not supported in compile-time checks at the moment.

Argument Lists

You can create your own formatting function with compile-time checks and small binary footprint, for example (https://godbolt.org/z/oba4Mc):

#include <fmt/format.h>

void vlog(const char* file, int line, fmt::string_view format,
          fmt::format_args args) {
  fmt::print("{}: {}: ", file, line);
  fmt::vprint(format, args);
}

template <typename S, typename... Args>
void log(const char* file, int line, const S& format, Args&&... args) {
  vlog(file, line, format,
      fmt::make_args_checked<Args...>(format, args...));
}

#define MY_LOG(format, ...) \
  log(__FILE__, __LINE__, FMT_STRING(format), __VA_ARGS__)

MY_LOG("invalid squishiness: {}", 42);

Note that vlog is not parameterized on argument types which improves compile times and reduces binary code size compared to a fully parameterized version.

template <typename... Args, typename S, typename Char = char_t<S>>
auto fmt::make_args_checked(const S &format_str, const remove_reference_t<Args>&... args)

Constructs a format_arg_store object that contains references to arguments and can be implicitly converted to format_args. If format_str is a compile-time string then make_args_checked checks its validity at compile time.

template <typename Context = format_context, typename... Args>
format_arg_store<Context, Args...> fmt::make_format_args(const Args&... args)

Constructs a format_arg_store object that contains references to arguments and can be implicitly converted to format_args. Context can be omitted in which case it defaults to context. See arg() for lifetime considerations.

template <typename Context, typename... Args>
class fmt::format_arg_store

An array of references to arguments. It can be implicitly converted into basic_format_args for passing into type-erased formatting functions such as vformat().

template <typename Context>
class fmt::dynamic_format_arg_store

A dynamic version of fmt::format_arg_store. It’s equipped with a storage to potentially temporary objects which lifetimes could be shorter than the format arguments object.

It can be implicitly converted into basic_format_args for passing into type-erased formatting functions such as vformat().

Public Functions

template <typename T>
void push_back(const T &arg)

Adds an argument into the dynamic store for later passing to a formatting function.

Note that custom types and string types (but not string views) are copied into the store dynamically allocating memory if necessary.

Example:

fmt::dynamic_format_arg_store<fmt::format_context> store;
store.push_back(42);
store.push_back("abc");
store.push_back(1.5f);
std::string result = fmt::vformat("{} and {} and {}", store);

template <typename T>
void push_back(std::reference_wrapper<T> arg)

Adds a reference to the argument into the dynamic store for later passing to a formatting function. Supports named arguments wrapped in std::reference_wrapper via std::ref()/std::cref().

Example:

fmt::dynamic_format_arg_store<fmt::format_context> store;
char str[] = "1234567890";
store.push_back(std::cref(str));
int a1_val{42};
auto a1 = fmt::arg("a1_", a1_val);
store.push_back(std::cref(a1));

// Changing str affects the output but only for string and custom types.
str[0] = 'X';

std::string result = fmt::vformat("{} and {a1_}");
assert(result == "X234567890 and 42");

template <typename T>
void push_back(const detail::named_arg<char_type, T> &arg)

Adds named argument into the dynamic store for later passing to a formatting function.

std::reference_wrapper is supported to avoid copying of the argument.

void clear()

Erase all elements from the store.

void reserve(size_t new_cap, size_t new_cap_named)

Reserves space to store at least new_cap arguments including new_cap_named named arguments.

template <typename Context>
class fmt::basic_format_args

A view of a collection of formatting arguments. To avoid lifetime issues it should only be used as a parameter type in type-erased functions such as vformat:

void vlog(string_view format_str, format_args args);  // OK
format_args args = make_format_args(42);  // Error: dangling reference

Public Functions

template <typename... Args>
basic_format_args(const format_arg_store<Context, Args...> &store)

Constructs a basic_format_args object from format_arg_store.

basic_format_args(const dynamic_format_arg_store<Context> &store)

Constructs a basic_format_args object from dynamic_format_arg_store.

basic_format_args(const format_arg *args, int count)

Constructs a basic_format_args object from a dynamic set of arguments.

format_arg get(int id) const

Returns the argument with the specified id.

struct fmt::format_args

An alias to basic_format_args<context>.

Inherits from fmt::basic_format_args< format_context >

template <typename Context>
class fmt::basic_format_arg

Compatibility

template <typename Char>
class fmt::basic_string_view

An implementation of std::basic_string_view for pre-C++17.

It provides a subset of the API. fmt::basic_string_view is used for format strings even if std::string_view is available to prevent issues when a library is compiled with a different -std option than the client code (which is not recommended).

Public Functions

constexpr basic_string_view(const Char *s, size_t count)

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

basic_string_view(const Char *s)

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

template <typename Traits, typename Alloc>
basic_string_view(const std::basic_string<Char, Traits, Alloc> &s)

Constructs a string reference from a std::basic_string object.

constexpr const Char *data() const

Returns a pointer to the string data.

constexpr size_t size() const

Returns the string size.

using fmt::string_view = typedef basic_string_view<char>
using fmt::wstring_view = typedef basic_string_view<wchar_t>

Locale

All formatting is locale-independent by default. Use the 'L' format specifier to insert the appropriate number separator characters from the locale:

#include <fmt/core.h>
#include <locale>

std::locale::global(std::locale("en_US.UTF-8"));
auto s = fmt::format("{:L}", 1000000);  // s == "1,000,000"

Format API

fmt/format.h defines the full format API providing compile-time format string checks, wide string, output iterator and user-defined type support.

Compile-time Format String Checks

Compile-time checks are enabled when using FMT_STRING. They support built-in and string types as well as user-defined types with constexpr parse functions in their formatter specializations.

FMT_STRING(s)

Constructs a compile-time format string from a string literal s.

Example:

// A compile-time error because 'd' is an invalid specifier for strings.
std::string s = fmt::format(FMT_STRING("{:d}"), "foo");

Formatting User-defined Types

To make a user-defined type formattable, specialize the formatter<T> struct template and implement parse and format methods:

#include <fmt/format.h>

struct point { double x, y; };

template <>
struct fmt::formatter<point> {
  // Presentation format: 'f' - fixed, 'e' - exponential.
  char presentation = 'f';

  // Parses format specifications of the form ['f' | 'e'].
  constexpr auto parse(format_parse_context& ctx) {
  // auto parse(format_parse_context &ctx) -> decltype(ctx.begin()) // c++11
    // [ctx.begin(), ctx.end()) is a character range that contains a part of
    // the format string starting from the format specifications to be parsed,
    // e.g. in
    //
    //   fmt::format("{:f} - point of interest", point{1, 2});
    //
    // the range will contain "f} - point of interest". The formatter should
    // parse specifiers until '}' or the end of the range. In this example
    // the formatter should parse the 'f' specifier and return an iterator
    // pointing to '}'.

    // Parse the presentation format and store it in the formatter:
    auto it = ctx.begin(), end = ctx.end();
    if (it != end && (*it == 'f' || *it == 'e')) presentation = *it++;

    // Check if reached the end of the range:
    if (it != end && *it != '}')
      throw format_error("invalid format");

    // Return an iterator past the end of the parsed range:
    return it;
  }

  // Formats the point p using the parsed format specification (presentation)
  // stored in this formatter.
  template <typename FormatContext>
  auto format(const point& p, FormatContext& ctx) {
  // auto format(const point &p, FormatContext &ctx) -> decltype(ctx.out()) // c++11
    // ctx.out() is an output iterator to write to.
    return format_to(
        ctx.out(),
        presentation == 'f' ? "({:.1f}, {:.1f})" : "({:.1e}, {:.1e})",
        p.x, p.y);
  }
};

Then you can pass objects of type point to any formatting function:

point p = {1, 2};
std::string s = fmt::format("{:f}", p);
// s == "(1.0, 2.0)"

You can also reuse existing formatters via inheritance or composition, for example:

enum class color {red, green, blue};

template <> struct fmt::formatter<color>: formatter<string_view> {
  // parse is inherited from formatter<string_view>.
  template <typename FormatContext>
  auto format(color c, FormatContext& ctx) {
    string_view name = "unknown";
    switch (c) {
    case color::red:   name = "red"; break;
    case color::green: name = "green"; break;
    case color::blue:  name = "blue"; break;
    }
    return formatter<string_view>::format(name, ctx);
  }
};

Since parse is inherited from formatter<string_view> it will recognize all string format specifications, for example

fmt::format("{:>10}", color::blue)

will return "      blue".

You can also write a formatter for a hierarchy of classes:

#include <type_traits>
#include <fmt/format.h>

struct A {
  virtual ~A() {}
  virtual std::string name() const { return "A"; }
};

struct B : A {
  virtual std::string name() const { return "B"; }
};

template <typename T>
struct fmt::formatter<T, std::enable_if_t<std::is_base_of<A, T>::value, char>> :
    fmt::formatter<std::string> {
  template <typename FormatCtx>
  auto format(const A& a, FormatCtx& ctx) {
    return fmt::formatter<std::string>::format(a.name(), ctx);
  }
};

int main() {
  B b;
  A& a = b;
  fmt::print("{}", a); // prints "B"
}

If a type provides both a formatter specialization and an implicit conversion to a formattable type, the specialization takes precedence over the conversion.

template <typename Char, typename ErrorHandler = detail::error_handler>
class fmt::basic_format_parse_context

Parsing context consisting of a format string range being parsed and an argument counter for automatic indexing.

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

Type Definition
format_parse_context basic_format_parse_context<char>
wformat_parse_context basic_format_parse_context<wchar_t>

Inherits from ErrorHandler

Subclassed by fmt::detail::compile_parse_context< Char, ErrorHandler >

Public Functions

constexpr iterator begin() const

Returns an iterator to the beginning of the format string range being parsed.

constexpr iterator end() const

Returns an iterator past the end of the format string range being parsed.

void advance_to(iterator it)

Advances the begin iterator to it.

int next_arg_id()

Reports an error if using the manual argument indexing; otherwise returns the next argument index and switches to the automatic indexing.

void check_arg_id(int)

Reports an error if using the automatic argument indexing; otherwise switches to the manual indexing.

Output Iterator Support

template <typename OutputIt, typename S, typename... Args>
OutputIt fmt::format_to(OutputIt out, const S &format_str, Args&&... args)

Formats arguments, writes the result to the output iterator out and returns the iterator past the end of the output range.

Example:

std::vector<char> out;
fmt::format_to(std::back_inserter(out), "{}", 42);

template <typename OutputIt, typename S, typename... Args>
format_to_n_result<OutputIt> fmt::format_to_n(OutputIt out, size_t n, const S &format_str, const Args&... args)

Formats arguments, writes up to n characters of the result to the output iterator out and returns the total output size and the iterator past the end of the output range.

template <typename OutputIt>
struct fmt::format_to_n_result

Public Members

OutputIt out

Iterator past the end of the output range.

size_t size

Total (not truncated) output size.

Literal-based API

The following user-defined literals are defined in fmt/format.h.

detail::udl_formatter<char> fmt::literals::operator""_format(const char *s, size_t n)

User-defined literal equivalent of fmt::format().

Example:

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

detail::udl_arg<char> fmt::literals::operator""_a(const char *s, size_t)

User-defined literal equivalent of fmt::arg().

Example:

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

Utilities

template <typename T>
struct fmt::is_char

Specifies if T is a character type.

Can be specialized by users.

Inherits from false_type

using fmt::char_t = typedef typename detail::char_t_impl<S>::type

String’s character type.

template <typename T>
std::string fmt::to_string(const T &value)

Converts value to std::string using the default format for type T.

Example:

#include <fmt/format.h>

std::string answer = fmt::to_string(42);

template <typename T>
std::wstring fmt::to_wstring(const T &value)

Converts value to std::wstring using the default format for type T.

template <typename Char>
basic_string_view<Char> fmt::to_string_view(const Char *s)

Returns a string view of s. In order to add custom string type support to {fmt} provide an overload of to_string_view for it in the same namespace as the type for the argument-dependent lookup to work.

Example:

namespace my_ns {
inline string_view to_string_view(const my_string& s) {
  return {s.data(), s.length()};
}
}
std::string message = fmt::format(my_string("The answer is {}"), 42);

Warning

doxygenfunction: Unable to resolve multiple matches for function “fmt::join” with arguments (const Range&, string_view) in doxygen xml output for project “format” from directory: /home/travis/build/fmtlib/fmt/doxyxml. Potential matches:

- template <typename It, typename Sentinel>
  arg_join<It, Sentinel, char> fmt::join(It, Sentinel, string_view)
- template <typename It, typename Sentinel>
  arg_join<It, Sentinel, wchar_t> fmt::join(It, Sentinel, wstring_view)
- template <typename Range>
  arg_join<detail::iterator_t<Range>, detail::sentinel_t<Range>, char> fmt::join(Range&&, string_view)
- template <typename Range>
  arg_join<detail::iterator_t<Range>, detail::sentinel_t<Range>, wchar_t> fmt::join(Range&&, wstring_view)
template <typename It, typename Sentinel>
arg_join<It, Sentinel, char> fmt::join(It begin, Sentinel end, string_view sep)

Returns an object that formats the iterator range [begin, end) with elements separated by sep.

template <typename T>
class fmt::detail::buffer

A contiguous memory buffer with an optional growing ability. It is an internal class and shouldn’t be used directly, only via basic_memory_buffer.

Subclassed by fmt::basic_memory_buffer< T, SIZE, Allocator >, fmt::detail::counting_buffer< T >, fmt::detail::iterator_buffer< OutputIt, T, Traits >, fmt::detail::iterator_buffer< T *, T >

Public Functions

size_t size() const

Returns the size of this buffer.

size_t capacity() const

Returns the capacity of this buffer.

T *data()

Returns a pointer to the buffer data.

const T *data() const

Returns a pointer to the buffer data.

void clear()

Clears this buffer.

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

Appends data to the end of the buffer.

template <typename T, size_t SIZE = inline_buffer_size, typename Allocator = std::allocator<T>>
class fmt::basic_memory_buffer

A dynamically growing memory buffer for trivially copyable/constructible types with the first SIZE elements stored in the object itself.

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

Type Definition
memory_buffer basic_memory_buffer<char>
wmemory_buffer basic_memory_buffer<wchar_t>

Example:

fmt::memory_buffer out;
format_to(out, "The answer is {}.", 42);

This will append the following output to the out object:

The answer is 42.

The output can be converted to an std::string with to_string(out).

Inherits from fmt::detail::buffer< T >

Public Functions

basic_memory_buffer(basic_memory_buffer &&other)

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

basic_memory_buffer &operator=(basic_memory_buffer &&other)

Moves the content of the other basic_memory_buffer object to this one.

void resize(size_t count)

Resizes the buffer to contain count elements.

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

void reserve(size_t new_capacity)

Increases the buffer capacity to new_capacity.

Protected Functions

void grow(size_t capacity)

Increases the buffer capacity to hold at least capacity elements.

System Errors

fmt does not use errno to communicate errors to the user, but it may call system functions which set errno. Users should not make any assumptions about the value of errno being preserved by library functions.

class fmt::system_error

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

Inherits from runtime_error

Subclassed by fmt::windows_error

Public Functions

template <typename... Args>
system_error(int error_code, string_view message, const Args&... args)

Constructs a fmt::system_error object with a description formatted with fmt::format_system_error(). message and additional arguments passed into the constructor are formatted similarly to fmt::format().

Example:

// This throws a system_error 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::system_error(errno, "cannot open file '{}'", filename);

void fmt::format_system_error(detail::buffer<char> &out, int error_code, string_view message)

Formats an error returned by an operating system or a language runtime, for example a file opening error, and writes it to out in the following form:

<message>: <system-message>

where <message> is the passed 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.

class fmt::windows_error

A Windows error.

Inherits from fmt::system_error

Public Functions

template <typename... Args>
windows_error(int error_code, string_view message, const Args&... args)

Constructs a fmt::windows_error 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 windows_error 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::windows_error(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::basic_memory_buffer:

using custom_memory_buffer =
  fmt::basic_memory_buffer<char, fmt::inline_buffer_size, custom_allocator>;

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

using custom_string =
  std::basic_string<char, std::char_traits<char>, custom_allocator>;

custom_string vformat(custom_allocator alloc, fmt::string_view format_str,
                      fmt::format_args args) {
  custom_memory_buffer buf(alloc);
  fmt::vformat_to(buf, format_str, args);
  return custom_string(buf.data(), buf.size(), alloc);
}

template <typename ...Args>
inline custom_string format(custom_allocator alloc,
                            fmt::string_view format_str,
                            const Args& ... args) {
  return vformat(alloc, format_str, fmt::make_format_args(args...));
}

The allocator will be used for the output container only. Formatting functions normally don’t do any allocations for built-in and string types except for non-default floating-point formatting that occasionally falls back on sprintf.

Ranges and Tuple Formatting

The library also supports convenient formatting of ranges and tuples:

#include <fmt/ranges.h>

std::tuple<char, int, float> t{'a', 1, 2.0f};
// Prints "('a', 1, 2.0)"
fmt::print("{}", t);

NOTE: currently, the overload of fmt::join for iterables exists in the main format.h header, but expect this to change in the future.

Using fmt::join, you can separate tuple elements with a custom separator:

#include <fmt/ranges.h>

std::tuple<int, char> t = {1, 'a'};
// Prints "1, a"
fmt::print("{}", fmt::join(t, ", "));

Date and Time Formatting

The library supports strftime-like date and time formatting:

#include <fmt/chrono.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}.", fmt::localtime(t));

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

Format string compilation

fmt/compile.h provides format string compilation support when using FMT_COMPILE. Format strings are parsed, checked and converted into efficient formatting code at compile-time. This supports arguments of built-in and string types as well as user-defined types with constexpr parse functions in their formatter specializations. Format string compilation can generate more binary code compared to the default API and is only recommended in places where formatting is a performance bottleneck.

FMT_COMPILE(s)

Converts a string literal s into a format string that will be parsed at compile time and converted into efficient formatting code. Requires C++17 constexpr if compiler support.

Example:

// Converts 42 into std::string using the most efficient method and no
// runtime format string processing.
std::string s = fmt::format(FMT_COMPILE("{}"), 42);

Terminal color and text style

fmt/color.h provides support for terminal color and text style output.

enum fmt::color

Values:

alice_blue = 0xF0F8FF
antique_white = 0xFAEBD7
aqua = 0x00FFFF
aquamarine = 0x7FFFD4
azure = 0xF0FFFF
beige = 0xF5F5DC
bisque = 0xFFE4C4
black = 0x000000
blanched_almond = 0xFFEBCD
blue = 0x0000FF
blue_violet = 0x8A2BE2
brown = 0xA52A2A
burly_wood = 0xDEB887
cadet_blue = 0x5F9EA0
chartreuse = 0x7FFF00
chocolate = 0xD2691E
coral = 0xFF7F50
cornflower_blue = 0x6495ED
cornsilk = 0xFFF8DC
crimson = 0xDC143C
cyan = 0x00FFFF
dark_blue = 0x00008B
dark_cyan = 0x008B8B
dark_golden_rod = 0xB8860B
dark_gray = 0xA9A9A9
dark_green = 0x006400
dark_khaki = 0xBDB76B
dark_magenta = 0x8B008B
dark_olive_green = 0x556B2F
dark_orange = 0xFF8C00
dark_orchid = 0x9932CC
dark_red = 0x8B0000
dark_salmon = 0xE9967A
dark_sea_green = 0x8FBC8F
dark_slate_blue = 0x483D8B
dark_slate_gray = 0x2F4F4F
dark_turquoise = 0x00CED1
dark_violet = 0x9400D3
deep_pink = 0xFF1493
deep_sky_blue = 0x00BFFF
dim_gray = 0x696969
dodger_blue = 0x1E90FF
fire_brick = 0xB22222
floral_white = 0xFFFAF0
forest_green = 0x228B22
fuchsia = 0xFF00FF
gainsboro = 0xDCDCDC
ghost_white = 0xF8F8FF
gold = 0xFFD700
golden_rod = 0xDAA520
gray = 0x808080
green = 0x008000
green_yellow = 0xADFF2F
honey_dew = 0xF0FFF0
hot_pink = 0xFF69B4
indian_red = 0xCD5C5C
indigo = 0x4B0082
ivory = 0xFFFFF0
khaki = 0xF0E68C
lavender = 0xE6E6FA
lavender_blush = 0xFFF0F5
lawn_green = 0x7CFC00
lemon_chiffon = 0xFFFACD
light_blue = 0xADD8E6
light_coral = 0xF08080
light_cyan = 0xE0FFFF
light_golden_rod_yellow = 0xFAFAD2
light_gray = 0xD3D3D3
light_green = 0x90EE90
light_pink = 0xFFB6C1
light_salmon = 0xFFA07A
light_sea_green = 0x20B2AA
light_sky_blue = 0x87CEFA
light_slate_gray = 0x778899
light_steel_blue = 0xB0C4DE
light_yellow = 0xFFFFE0
lime = 0x00FF00
lime_green = 0x32CD32
linen = 0xFAF0E6
magenta = 0xFF00FF
maroon = 0x800000
medium_aquamarine = 0x66CDAA
medium_blue = 0x0000CD
medium_orchid = 0xBA55D3
medium_purple = 0x9370DB
medium_sea_green = 0x3CB371
medium_slate_blue = 0x7B68EE
medium_spring_green = 0x00FA9A
medium_turquoise = 0x48D1CC
medium_violet_red = 0xC71585
midnight_blue = 0x191970
mint_cream = 0xF5FFFA
misty_rose = 0xFFE4E1
moccasin = 0xFFE4B5
navajo_white = 0xFFDEAD
navy = 0x000080
old_lace = 0xFDF5E6
olive = 0x808000
olive_drab = 0x6B8E23
orange = 0xFFA500
orange_red = 0xFF4500
orchid = 0xDA70D6
pale_golden_rod = 0xEEE8AA
pale_green = 0x98FB98
pale_turquoise = 0xAFEEEE
pale_violet_red = 0xDB7093
papaya_whip = 0xFFEFD5
peach_puff = 0xFFDAB9
peru = 0xCD853F
pink = 0xFFC0CB
plum = 0xDDA0DD
powder_blue = 0xB0E0E6
purple = 0x800080
rebecca_purple = 0x663399
red = 0xFF0000
rosy_brown = 0xBC8F8F
royal_blue = 0x4169E1
saddle_brown = 0x8B4513
salmon = 0xFA8072
sandy_brown = 0xF4A460
sea_green = 0x2E8B57
sea_shell = 0xFFF5EE
sienna = 0xA0522D
silver = 0xC0C0C0
sky_blue = 0x87CEEB
slate_blue = 0x6A5ACD
slate_gray = 0x708090
snow = 0xFFFAFA
spring_green = 0x00FF7F
steel_blue = 0x4682B4
tan = 0xD2B48C
teal = 0x008080
thistle = 0xD8BFD8
tomato = 0xFF6347
turquoise = 0x40E0D0
violet = 0xEE82EE
wheat = 0xF5DEB3
white = 0xFFFFFF
white_smoke = 0xF5F5F5
yellow = 0xFFFF00
yellow_green = 0x9ACD32
template <typename S, typename... Args>
void fmt::print(const text_style &ts, const S &format_str, const Args&... args)

Formats a string and prints it to stdout using ANSI escape sequences to specify text formatting.

Example: fmt::print(fmt::emphasis::bold | fg(fmt::color::red), “Elapsed time: {0:.2f} seconds”, 1.23);

std::ostream Support

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"
template <typename S, typename... Args, typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
void fmt::print(std::basic_ostream<Char> &os, const S &format_str, Args&&... args)

Prints formatted data to the stream os.

Example:

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

printf Formatting

The header fmt/printf.h provides printf-like formatting functionality. The following functions use printf format string syntax with the POSIX extension for positional arguments. Unlike their standard counterparts, the fmt functions are type-safe and throw an exception if an argument type doesn’t match its format specification.

template <typename S, typename... Args>
int fmt::printf(const S &format_str, const Args&... args)

Prints formatted data to stdout.

Example:

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

template <typename S, typename... Args, typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
int fmt::fprintf(std::FILE *f, const S &format, const Args&... args)

Prints formatted data to the file f.

Example:

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

template <typename S, typename... Args, typename Char = char_t<S>>
int fmt::fprintf(std::basic_ostream<Char> &os, const S &format_str, const Args&... args)

Prints formatted data to the stream os.

Example:

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

template <typename S, typename... Args, typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
std::basic_string<Char> fmt::sprintf(const S &format, const Args&... args)

Formats arguments and returns the result as a string.

Example:

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

Compatibility with C++20 std::format

{fmt} implements nearly all of the C++20 formatting library with the following differences:

  • Names are defined in the fmt namespace instead of std to avoid collisions with standard library implementations.
  • The 'L' format specifier cannot be combined with presentation specifiers yet.
  • Width calculation doesn’t use grapheme clusterization. The latter has been implemented in a separate branch but hasn’t been integrated yet.
  • Chrono formatting doesn’t support C++20 date types since they are not provided by standard library implementations.