API Reference

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

Formatting functions

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(StringRef format_str, ArgList args)

Formats arguments and returns the result as a string.

Example:

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

void fmt::print(StringRef format_str, ArgList args)

Prints formatted data to stdout.

Example:

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

Warning

doxygenfunction: Unable to resolve multiple matches for function “print” with arguments (std::FILE*, StringRef, ArgList) in doxygen xml output for project “project0” from directory: /build/cppformat-0sNCni/cppformat-1.1.0+ds/obj-i686-linux-gnu/doc/doxyxml. Potential matches:

- void fmt::print(std::FILE *, StringRef, ArgList)
- void fmt::print(StringRef, ArgList)
- void fmt::print(std::ostream&, StringRef, ArgList)
void fmt::print(std::ostream &os, StringRef format_str, ArgList args)

Prints formatted data to the stream os.

Example:

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

Printf formatting functions

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

int fmt::printf(StringRef format, ArgList args)

Prints formatted data to stdout.

Example:

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

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

Prints formatted data to the file f.

Example:

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

std::string fmt::sprintf(StringRef 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(BasicStringRef<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.

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.

Warning

doxygenfunction: Unable to resolve multiple matches for function “pad” with arguments (int, unsigned int, Char) in doxygen xml output for project “project0” from directory: /build/cppformat-0sNCni/cppformat-1.1.0+ds/obj-i686-linux-gnu/doc/doxyxml. Potential matches:

- template <typename Char>
  StrFormatSpec<Char> fmt::pad(const Char *, unsigned, Char)
- template <char, typename Char>
  IntFormatSpec<int, AlignTypeSpec<TYPE_CODE>, Char> fmt::pad(int, unsigned, Char)
- StrFormatSpec<wchar_t> fmt::pad(const wchar_t *, unsigned, char)

Utilities

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.

operator std::basic_string<Char>() const

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

const Char *c_str() const

Returns the pointer to a C string.

std::size_t size() const

Returns the string size.

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, StringRef 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, StringRef 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 C++ Format 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::StringRef 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::StringRef)