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.
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.
Formats arguments and returns the result as a string.
Example:
std::string message = format("The answer is {}", 42);
Prints formatted data to stdout.
Example:
print("Elapsed time: {0:.2f} seconds", 1.23);
Prints formatted data to the file f.
Example:
print(stderr, "Don't {}!", "panic");
Prints formatted data to the stream os.
Example:
print(cerr, "Don't {}!", "panic");
The following functions use printf format string syntax with a POSIX extension for positional arguments.
Prints formatted data to stdout.
Example:
fmt::printf("Elapsed time: %.2f seconds", 1.23);
Prints formatted data to the file f.
Example:
fmt::fprintf(stderr, "Don't %s!", "panic");
Formats arguments and returns the result as a string.
Example:
std::string message = fmt::sprintf("The answer is %d", 42);
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
Destroys a BasicWriter object.
Returns the total number of characters written.
Returns a pointer to the output buffer content.
No terminating null character is appended.
Returns a pointer to the output buffer content with terminating null character appended.
Returns the content of the output buffer as an std::string.
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.
Formats value and writes it to the stream.
Formats value using the general format for floating-point numbers ('g') and writes it to the stream.
Writes a character to the stream.
Writes value to the stream.
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
Constructs a fmt::BasicMemoryWriter object moving the content of the other object to it.
Moves the content of the other BasicMemoryWriter object to this one.
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
Constructs a fmt::BasicArrayWriter object for array of the given size.
Returns an integer format specifier to format the value in base 2.
Returns an integer format specifier to format the value in base 8.
Returns an integer format specifier to format the value in base 16 using lower-case letters for the digits above 9.
Returns an integer formatter format specifier to format in base 16 using upper-case letters for the digits above 9.
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"
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...);
}
An argument list.
Public Functions
Returns the argument at specified index.
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
Constructs a string reference object from a C string and a size.
Constructs a string reference object from a C string computing the size with std::char_traits<Char>length.
Constructs a string reference from an std::string object.
Converts a string reference to an std::string object.
Returns the pointer to a C string.
Returns the string size.
An error returned by an operating system or a language runtime, for example a file opening error.
Public Functions
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);
A Windows error.
Public Functions
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);
}
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)