Janis Lesinskis' Blog

Assorted ramblings

  • All entries
  • About me
  • Projects
  • Economics
  • Misc
  • Software-engineering
  • Sports

The fmt library


One of the things I really like about Python is the string formatting support in the language.

This was always one of the things I found a bit clunky when I would be going back and forth coding in C++. Sure there's printf but printf doesn't have great support for user types. Recently I came across the fmt library and I'm very happy with what I see there (so far).

Basically this library gives you good support for creating formatted strings in C++. It supplies a nice domain specific language for formatting that's much like the Python one, very easy to use and has good support for types. It also has good performance so you aren't paying a high price for the convenience either.

For example, let's say I'd like to format a decimal to have 3 decimal places, here's how I'd have to do it with "regular" c++:

std::cout << std::setprecision(3) << std::fixed << 1.23456 << "\n";

And here's what this looks like with the fmt library:

fmt::format("{:.3f}", 1.23456);

There's other things that fmt makes quite easy too like writing to a file:

#include <fmt/os.h>

int main() {
  auto out = fmt::output_file("guide.txt");
  out.print("Don't {}", "Panic");
}

I like that this benchmarks faster than printf as well.

Published: Fri 26 March 2021
By Janis Lesinskis
In Software-engineering
Tags: python c++ printf string-formatting strings formatting

links

  • JaggedVerge

social

  • My GitHub page
  • LinkedIn

Proudly powered by Pelican, which takes great advantage of Python.