API Reference¶
The {fmt} library API consists of the following parts:
fmt/core.h: the core API providing main formatting functions for
char
/UTF-8 with C++20 compile-time checks and minimal dependenciesfmt/format.h: the full format API providing additional formatting functions and locale support
fmt/ranges.h: formatting of ranges and tuples
fmt/chrono.h: date and time formatting
fmt/std.h: formatters for standard library types
fmt/compile.h: format string compilation
fmt/color.h: terminal color and text style
fmt/os.h: system APIs
fmt/ostream.h:
std::ostream
supportfmt/printf.h:
printf
formattingfmt/xchar.h: optional
wchar_t
support
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 main formatting functions
for char
/UTF-8 with C++20 compile-time checks. It has minimal include
dependencies for better compile times. This header is only beneficial when
using {fmt} as a library and not in the header-only mode.
The following functions use format string syntax similar to that of Python’s str.format. They take fmt and args as arguments.
fmt 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. format_string
is a format string which can be
implicitly constructed from a string literal or a constexpr
string and is
checked at compile time in C++20. To pass a runtime format string wrap it in
fmt::runtime()
.
args is an argument list representing objects to be formatted.
-
template<typename ...T>
inline auto fmt::format(format_string<T...> fmt, T&&... args) -> std::string¶ Formats
args
according to specifications infmt
and returns the result as a string.Example:
#include <fmt/core.h> std::string message = fmt::format("The answer is {}.", 42);
-
auto fmt::vformat(string_view fmt, format_args args) -> std::string¶
-
template<typename OutputIt, typename ...T>
inline auto fmt::format_to(OutputIt out, format_string<T...> fmt, T&&... args) -> OutputIt¶ Formats
args
according to specifications infmt
, writes the result to the output iteratorout
and returns the iterator past the end of the output range.format_to()
does not append a terminating null character.Example:
auto out = std::vector<char>(); fmt::format_to(std::back_inserter(out), "{}", 42);
-
template<typename OutputIt, typename ...T>
inline auto fmt::format_to_n(OutputIt out, size_t n, format_string<T...> fmt, T&&... args) -> format_to_n_result<OutputIt>¶ Formats
args
according to specifications infmt
, writes up ton
characters of the result to the output iteratorout
and returns the total (not truncated) output size and the iterator past the end of the output range.format_to_n()
does not append a terminating null character.
-
template<typename ...T>
inline auto fmt::formatted_size(format_string<T...> fmt, T&&... args) -> size_t¶ Returns the number of chars in the output of
format(fmt, args...)
.
-
template<typename OutputIt>
struct format_to_n_result¶
-
template<typename ...T>
inline void fmt::print(format_string<T...> fmt, T&&... args)¶ Formats
args
according to specifications infmt
and writes the output tostdout
.Example:
fmt::print("Elapsed time: {0:.2f} seconds", 1.23);
-
void fmt::vprint(string_view fmt, format_args args)¶
-
template<typename ...T>
inline void fmt::print(std::FILE *f, format_string<T...> fmt, T&&... args)¶ Formats
args
according to specifications infmt
and writes the output to the filef
.Example:
fmt::print(stderr, "Don't {}!", "panic");
-
void fmt::vprint(std::FILE *f, string_view fmt, format_args args)¶
Compile-Time Format String Checks¶
Compile-time checks are enabled by default on compilers that support C++20
consteval
. On older compilers you can use the FMT_STRING
macro defined
in fmt/format.h
instead. It requires C++14 and is a no-op in C++11.
-
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");
To force the use of legacy compile-time checks, define the preprocessor variable
FMT_ENFORCE_COMPILE_STRING
. When set, functions accepting FMT_STRING
will fail to compile with regular strings. Runtime-checked formatting is still
possible using fmt::vformat
, fmt::vprint
, etc.
-
template<typename Char, typename ...Args>
class basic_format_string¶ A compile-time format string.
-
template<typename ...Args>
using fmt::format_string = basic_format_string<char, type_identity_t<Args>...>¶
-
inline auto fmt::runtime(string_view s) -> basic_runtime<char>¶
Creates a runtime format string.
Example:
// Check format string at runtime instead of compile-time. fmt::print(fmt::runtime("{:d}"), "I am not a number");
Named Arguments¶
Warning
doxygenfunction: Unable to resolve function “fmt::arg” with arguments (const S&, const T&) in doxygen xml output for project “format” from directory: ../bdir/doxyxml. Potential matches:
- template<typename Char, typename T> auto arg(const Char *name, const T &arg) -> detail::named_arg<Char, T>
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_format_args(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.
Warning
doxygenfunction: Unable to resolve function “fmt::make_format_args” with arguments (const Args&…) in doxygen xml output for project “format” from directory: ../bdir/doxyxml. Potential matches:
- template<typename Context = format_context, typename ...Args> constexpr auto make_format_args(Args&&... args) -> format_arg_store<Context, remove_cvref_t<Args>...>
-
template<typename Context, typename ...Args>
class 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 asvformat()
.
-
template<typename Context>
class dynamic_format_arg_store¶
-
template<typename Context>
class 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>
inline constexpr basic_format_args(const format_arg_store<Context, Args...> &store)¶ Constructs a
basic_format_args()
object fromformat_arg_store
.
-
inline constexpr basic_format_args(const dynamic_format_arg_store<Context> &store)¶
Constructs a
basic_format_args()
object fromdynamic_format_arg_store
.
-
inline constexpr basic_format_args(const format_arg *args, int count)¶
Constructs a
basic_format_args()
object from a dynamic set of arguments.
-
inline auto get(int id) const -> format_arg¶
Returns the argument with the specified id.
-
template<typename ...Args>
-
using fmt::format_args = basic_format_args<format_context>¶
An alias to
basic_format_args<format_context>
.
-
template<typename Context>
class basic_format_arg¶
-
template<typename Char, typename ErrorHandler = detail::error_handler>
class basic_format_parse_context : private fmt::detail::error_handler¶ Parsing context consisting of a format string range being parsed and an argument counter for automatic indexing. You can use the
format_parse_context
type alias forchar
instead.Subclassed by fmt::basic_printf_parse_context< Char >, fmt::detail::compile_parse_context< Char, ErrorHandler >
Public Functions
-
inline constexpr auto begin() const noexcept -> iterator¶
Returns an iterator to the beginning of the format string range being parsed.
-
inline constexpr auto end() const noexcept -> iterator¶
Returns an iterator past the end of the format string range being parsed.
-
inline void advance_to(iterator it)¶
Advances the begin iterator to
it
.
-
inline auto next_arg_id() -> int¶
Reports an error if using the manual argument indexing; otherwise returns the next argument index and switches to the automatic indexing.
-
inline void check_arg_id(int id)¶
Reports an error if using the automatic argument indexing; otherwise switches to the manual indexing.
-
inline constexpr auto begin() const noexcept -> iterator¶
-
template<typename OutputIt, typename Char>
class basic_format_context¶ -
Public Functions
-
inline constexpr basic_format_context(OutputIt out, basic_format_args<basic_format_context> ctx_args, detail::locale_ref loc = detail::locale_ref())¶
Constructs a
basic_format_context
object.References to the arguments are stored in the object so make sure they have appropriate lifetimes.
-
inline constexpr basic_format_context(OutputIt out, basic_format_args<basic_format_context> ctx_args, detail::locale_ref loc = detail::locale_ref())¶
-
using fmt::format_context = buffer_context<char>¶
Compatibility¶
-
template<typename Char>
class 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 ifstd::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
-
inline constexpr basic_string_view(const Char *s, size_t count) noexcept¶
Constructs a string reference object from a C string and a size.
-
inline 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>
inline basic_string_view(const std::basic_string<Char, Traits, Alloc> &s) noexcept¶ Constructs a string reference from a
std::basic_string
object.
-
inline constexpr auto size() const noexcept -> size_t¶
Returns the string size.
-
inline constexpr basic_string_view(const Char *s, size_t count) noexcept¶
-
using fmt::string_view = basic_string_view<char>¶
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 additional formatting
functions and locale support.
Formatting User-Defined Types¶
The {fmt} library provides formatters for many standard C++ types.
See fmt/ranges.h for ranges and tuples including standard
containers such as std::vector
, fmt/chrono.h for date
and time formatting and fmt/std.h for path and variant
formatting.
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) -> decltype(ctx.begin()) {
// [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 '}'.
// Please also note that this character range may be empty, in case of
// the "{}" format string, so therefore you should check ctx.begin()
// for equality with ctx.end().
// 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) const -> decltype(ctx.out()) {
// ctx.out() is an output iterator to write to.
return presentation == 'f'
? fmt::format_to(ctx.out(), "({:.1f}, {:.1f})", p.x, p.y)
: fmt::format_to(ctx.out(), "({:.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) const {
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) const {
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.
For enums {fmt} also provides the format_as
extension API. To format an enum
via this API define format_as
that takes this enum and converts it to the
underlying type. format_as
should be defined in the same namespace as the
enum.
Example (https://godbolt.org/z/r7vvGE1v7):
#include <fmt/format.h>
namespace kevin_namespacy {
enum class film {
house_of_cards, american_beauty, se7en = 7
};
auto format_as(film f) { return fmt::underlying(f); }
}
int main() {
fmt::print("{}\n", kevin_namespacy::film::se7en); // prints "7"
}
Literal-Based API¶
The following user-defined literals are defined in fmt/format.h
.
Warning
doxygenfunction: Unable to resolve function “operator””_a” with arguments () in doxygen xml output for project “format” from directory: ../bdir/doxyxml. Potential matches:
- constexpr auto operator""_a(const char *s, size_t) -> detail::udl_arg<char>
- constexpr detail::udl_arg<wchar_t> operator""_a(const wchar_t *s, size_t)
Utilities¶
-
template<typename T>
auto fmt::ptr(T p) -> const void*¶ Converts
p
toconst void*
for pointer formatting.Example:
auto s = fmt::format("{}", fmt::ptr(p));
-
template<typename Enum>
constexpr auto fmt::underlying(Enum e) noexcept -> underlying_t<Enum>¶ Converts
e
to the underlying type.Example:
enum class color { red, green, blue }; auto s = fmt::format("{}", fmt::underlying(color::red));
-
template<typename T>
inline auto fmt::to_string(const T &value) -> std::string¶ 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 Range>
auto fmt::join(Range &&range, string_view sep) -> join_view<detail::iterator_t<Range>, detail::sentinel_t<Range>>¶ Returns a view that formats
range
with elements separated bysep
.Example:
std::vector<int> v = {1, 2, 3}; fmt::print("{}", fmt::join(v, ", ")); // Output: "1, 2, 3"
fmt::join
applies passed format specifiers to the range elements:fmt::print("{:02}", fmt::join(v, ", ")); // Output: "01, 02, 03"
-
template<typename It, typename Sentinel>
auto fmt::join(It begin, Sentinel end, string_view sep) -> join_view<It, Sentinel>¶ Returns a view that formats the iterator range
[begin, end)
with elements separated bysep
.
-
template<typename T>
auto fmt::group_digits(T value) -> group_digits_view<T>¶ Returns a view that formats an integer value using ‘,’ as a locale-independent thousands separator.
Example:
fmt::print("{}", fmt::group_digits(12345)); // Output: "12,345"
-
template<typename T>
class 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< bigit, bigits_capacity >, fmt::basic_memory_buffer< char >, fmt::basic_memory_buffer< wchar_t >, 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 >, fmt::detail::iterator_buffer< T *, T, fixed_buffer_traits >
-
template<typename T, size_t SIZE = inline_buffer_size, typename Allocator = std::allocator<T>>
class basic_memory_buffer : public fmt::detail::buffer<T>¶ A dynamically growing memory buffer for trivially copyable/constructible types with the first
SIZE
elements stored in the object itself.You can use the
memory_buffer
type alias forchar
instead.Example:
auto out = fmt::memory_buffer(); format_to(std::back_inserter(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
withto_string(out)
.Public Functions
-
inline basic_memory_buffer(basic_memory_buffer &&other) noexcept¶
Constructs a
fmt::basic_memory_buffer
object moving the content of the other object to it.
-
inline auto operator=(basic_memory_buffer &&other) noexcept -> basic_memory_buffer&¶
Moves the content of the other
basic_memory_buffer
object to this one.
-
inline void resize(size_t count)¶
Resizes the buffer to contain count elements.
If T is a POD type new elements may not be initialized.
-
inline void reserve(size_t new_capacity)¶
Increases the buffer capacity to new_capacity.
Protected Functions
-
virtual void grow(size_t size) override¶
Increases the buffer capacity to hold at least capacity elements.
-
inline basic_memory_buffer(basic_memory_buffer &&other) noexcept¶
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.
-
template<typename ...T>
auto fmt::system_error(int error_code, format_string<T...> fmt, T&&... args) -> std::system_error¶ Constructs
std::system_error
with a message formatted withfmt::format(fmt, args...)
.error_code is a system error code as given by
errno
.Example:
// This throws std::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, const char *message) noexcept¶
Formats an error message for an error returned by an operating system or a language runtime, for example a file opening error, and writes it to out. The format is the same as the one used by
std::system_error(ec, message)
whereec
isstd::error_code(error_code, std::generic_category()})
. It is implementation-defined but normally looks like:<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
.
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) {
auto buf = custom_memory_buffer(alloc);
fmt::vformat_to(std::back_inserter(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
.
Range 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¶
fmt/chrono.h
provides formatters for
The format syntax is described in Chrono Format Specifications.
Example:
#include <fmt/chrono.h>
int main() {
std::time_t t = std::time(nullptr);
// Prints "The date is 2020-11-07." (with the current date):
fmt::print("The date is {:%Y-%m-%d}.", fmt::localtime(t));
using namespace std::literals::chrono_literals;
// Prints "Default format: 42s 100ms":
fmt::print("Default format: {} {}\n", 42s, 100ms);
// Prints "strftime-like format: 03:15:30":
fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s);
}
Warning
doxygenfunction: Cannot find function “localtime” in doxygen xml output for project “format” from directory: ../bdir/doxyxml
Warning
doxygenfunction: Cannot find function “gmtime” in doxygen xml output for project “format” from directory: ../bdir/doxyxml
Standard Library Types Formatting¶
fmt/std.h
provides formatters for:
Formatting Variants¶
A std::variant
is only formattable if every variant alternative is formattable, and requires the
__cpp_lib_variant
library feature.
Example:
#include <fmt/std.h>
std::variant<char, float> v0{'x'};
// Prints "variant('x')"
fmt::print("{}", v0);
std::variant<std::monostate, char> v1;
// Prints "variant(monostate)"
Format String Compilation¶
fmt/compile.h
provides format string compilation enabled via the
FMT_COMPILE
macro or the _cf
user-defined literal. Format strings
marked with FMT_COMPILE
or _cf
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)¶
Warning
doxygenfunction: Cannot find function “operator””_cf” in doxygen xml output for project “format” from directory: ../bdir/doxyxml
Terminal Color and Text Style¶
fmt/color.h
provides support for terminal color and text style output.
-
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);
Warning
doxygenfunction: Unable to resolve function “fg” with arguments (detail::color_type) in doxygen xml output for project “format” from directory: ../bdir/doxyxml. Potential matches:
- text_style fg(detail::color_type foreground) noexcept
- text_style fg(detail::color_type foreground) noexcept
Warning
doxygenfunction: Unable to resolve function “bg” with arguments (detail::color_type) in doxygen xml output for project “format” from directory: ../bdir/doxyxml. Potential matches:
- text_style bg(detail::color_type background) noexcept
- text_style bg(detail::color_type background) noexcept
-
template<typename T>
auto fmt::styled(const T &value, text_style ts) -> detail::styled_arg<remove_cvref_t<T>>¶ Returns an argument that will be formatted using ANSI escape sequences, to be used in a formatting function.
Example:
fmt::print("Elapsed time: {0:.2f} seconds", fmt::styled(1.23, fmt::fg(fmt::color::green) | fmt::bg(fmt::color::blue)));
System APIs¶
-
class ostream : private fmt::detail::buffer<char>¶
A fast output stream which is not thread-safe.
Public Functions
-
template<typename ...T>
inline void print(format_string<T...> fmt, T&&... args)¶ Formats
args
according to specifications infmt
and writes the output to the file.
Friends
-
template<typename ...T>
friend ostream output_file(cstring_view path, T... params)¶ Opens a file for writing. Supported parameters passed in params:
<integer>
: Flags passed to open (file::WRONLY | file::CREATE | file::TRUNC
by default)buffer_size=<integer>
: Output buffer size
Example:
auto out = fmt::output_file("guide.txt"); out.print("Don't {}", "Panic");
-
template<typename ...T>
std::ostream
Support¶
fmt/ostream.h
provides std::ostream
support including formatting of
user-defined types that have an overloaded insertion operator (operator<<
).
In order to make a type formattable via std::ostream
you should provide a
formatter
specialization inherited from ostream_formatter
:
#include <fmt/ostream.h>
struct date {
int year, month, day;
friend std::ostream& operator<<(std::ostream& os, const date& d) {
return os << d.year << '-' << d.month << '-' << d.day;
}
};
template <> struct fmt::formatter<date> : ostream_formatter {};
std::string s = fmt::format("The date is {}", date{2012, 12, 9});
// s == "The date is 2012-12-9"
-
template<typename T>
auto fmt::streamed(const T &value) -> detail::streamed_view<T>¶ Returns a view that formats
value
via an ostreamoperator<<
.Example:
fmt::print("Current thread id: {}\n", fmt::streamed(std::this_thread::get_id()));
-
template<typename ...T>
void fmt::print(std::ostream &os, format_string<T...> fmt, T&&... 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 ...T>
inline auto fmt::printf(const S &fmt, const T&... args) -> int¶ Prints formatted data to
stdout
.Example:
fmt::printf("Elapsed time: %.2f seconds", 1.23);
-
template<typename S, typename ...T, typename Char = char_t<S>>
inline auto fmt::fprintf(std::FILE *f, const S &fmt, const T&... args) -> int¶ Prints formatted data to the file f.
Example:
fmt::fprintf(stderr, "Don't %s!", "panic");
-
template<typename S, typename ...T, typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
inline auto fmt::sprintf(const S &fmt, const T&... args) -> std::basic_string<Char>¶ Formats arguments and returns the result as a string.
Example:
std::string message = fmt::sprintf("The answer is %d", 42);
wchar_t
Support¶
The optional header fmt/xchar.h
provides support for wchar_t
and exotic
character types.
-
template<typename T>
struct is_char : public std::false_type¶ Specifies if
T
is a character type.Can be specialized by users.
Warning
doxygentypedef: Cannot find typedef “fmt::wstring_view” in doxygen xml output for project “format” from directory: ../bdir/doxyxml
-
using fmt::wformat_context = buffer_context<wchar_t>¶
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 ofstd
to avoid collisions with standard library implementations.Width calculation doesn’t use grapheme clusterization. The latter has been implemented in a separate branch but hasn’t been integrated yet.
Most C++20 chrono types are not supported yet.