Skip to content

Format

About fmt/format

  • fmt/format has been accepted into C++20
  • It has the best of printf and cout
  • Many compilers don't implement it yet
  • We still depend on <fmt/format.h>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
find_package(fmt QUIET)
if (NOT fmt_FOUND)
    FetchContent_Declare(
            fmt
            GIT_REPOSITORY https://github.com/fmtlib/fmt
            GIT_TAG        8.1.1
    )
    FetchContent_MakeAvailable(fmt)
endif()
add_executable(format format.cpp)
target_link_libraries(format fmt::fmt)

1
2
3
4
5
#include <fmt/chrono.h>  // time formatters
#include <fmt/color.h>   // color formatters
#include <fmt/format.h>  // main header
#include <fmt/ostream.h> // ostream formatters
#include <fmt/ranges.h>  // range formatters

1
fmt::print("Hello, world!\n");

1
std::cout << fmt::format("The answer is {}.\n", 42);

1
std::cout << fmt::format("I'd rather be {1} than {0}.\n", "right", "happy");

1
2
using namespace std::literals::chrono_literals;
fmt::print("Default format: {} {}\n", 42s, 100ms);

1
fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s);

1
2
std::vector<int> v = {1, 2, 3};
fmt::print("{}\n", v);

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

1
2
3
4
5
fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold, "Hello, {}!\n",
           "world");
auto style = fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) |
             fmt::emphasis::underline;
fmt::print(style, "Hello, {}!\n", "мир");

1
print(fg(fmt::color::steel_blue) | fmt::emphasis::italic, "Hello, {}!\n", "世界");

1
2
3
std::vector<char> out;
fmt::format_to(std::back_inserter(out), "For a moment, {} happened.", "nothing");
fmt::print("{}", out.data());

Share Snippets