I found this cool little text formatting library with very clean interface and wanted to share it with you. I decided the best way to introduce it to you is not through an extensive tutorial but rather code which illustrates how to use it; so I wrote a program which does the same thing in twelve different ways using this library… plus few extra examples of text coloring, formatting, and alignment. Take a look at the code and the program output and it will all make sense.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
#include <iostream> #include <string> #include <cstdlib> #include <fmt/core.h> #include <fmt/format.h> #include <fmt/time.h> #include <fmt/color.h> #include <fmt/printf.h> using namespace std; using namespace fmt; int main() { // Format into a std::string auto msg1 = fmt::format("The answer is {}", 42); auto msg2 = "{0}{1}"_format("The answer is ", 42); // Print std::string fmt::print("{}\n", msg1); fmt::print("{}\n", msg2); // Format into memory buffer and print fmt::memory_buffer out; format_to(out, "The answer is {0}", "42"); auto msg3 = string(out.begin(), out.end()); fmt::print("{}\n", msg3); // Reverse order of parameters, // print to various outputs fmt::print("{1} {0}\n", 42, "The answer is"); fmt::print(cout, "{1} {0}\n", 42, "The answer is"); fmt::print(stdout, "{1} {0}\n", 42, "The answer is"); // Named arguments fmt::print("{first} {second}\n", fmt::arg("first", "The answer is"), fmt::arg("second", 42)); fmt::print("{second} {first}\n", "second"_a="The answer is", "first"_a=42); // printf style formatting fmt::printf("The answer is %.2f\n", 42.f); fmt::fprintf(cout, "The answer is %.2f\n", 42.f); fmt::fprintf(stdout, "The answer is %.2f\n", 42.f); // printf style formatting into a std::string auto msg4 = fmt::sprintf("The answer is %.2f\n", 42.f); fmt::printf("%s", msg4); // Text color and style manipulation fmt::print(fmt::emphasis::bold, "The text is bold\n"); fmt::print(fmt::fg(fmt::color::red) | fmt::bg(fmt::color::green), "The color is red and green\n"); // Date and time formatting std::time_t t = std::time(nullptr); fmt::print("The date and time is {:%Y-%m-%d %H:%M:%S}\n", *std::localtime(&t)); // Alignment fmt::print("{:-<30}\n", "left aligned"); fmt::print("{:->30}\n", "right aligned"); fmt::print("{:-^30}\n", "centered"); } |
The answer is 42
Program output.
The answer is 42
The answer is 42
The answer is 42
The answer is 42
The answer is 42
The answer is 42
The answer is 42
The answer is 42.00
The answer is 42.00
The answer is 42.00
The answer is 42.00
The text is bold
The color is red and green
The date and time is 2019-03-31 09:03:45
left aligned——————
—————–right aligned
———–centered———–
are you using clang compiler maybe ? I need information about using clang and it’s properties.