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.
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");
-
void
fmt::
print
(std::ostream &os, CStringRef format_str, ArgList args)¶ Prints formatted data to the stream os.
Example:
print(cerr, "Don't {}!", "panic");
- template <typename Char>
-
class
fmt::
BasicFormatter
¶
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");
Warning
doxygenfunction: Unable to resolve multiple matches for function “fprintf” with arguments (std::ostream&, CStringRef, ArgList) in doxygen xml output for project “format” from directory: /home/viz/Downloads/1/cppformat-2.1.1/build/doc/doxyxml. Potential matches:
- int fmt::fprintf(std::FILE *, CStringRef, ArgList)
- template <typename...>
int fmt::fprintf(std::FILE *, CStringRef, const Args&...)
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()
orstr()
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.
-
virtual
- 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
without.str()
or accessed as a C string without.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.
-
internal::Arg
- 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 the pointer to a C string.
-
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);
- 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_
andcapacity_
.
-
std::size_t
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 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::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)