Nathaniel R. Stickley

Software Engineer - Astrophysicist - Data Scientist

The {fmt} Library

The standard options for formatting strings in C++ are, frankly, annoying and cumbersome. Yesterday, while using C++ stream format manipulators, I realized that someone must have come up with a clean solution to this common annoyance by now. So, I did a Google search for "C++ python-style string formatting" and eventually found the fmt library (formerly known as cppformat). Fmt is a lightweight library that allows you to use a syntax that is very similar to the string formatting mini-language supported by Python's str.format() function and the Rust language's string formatting syntax.

Here's a simple example:

The output of the program looks like this:

Hello World! This is the number 67
This is padded with zeros 0067 and this is not padded 45
Floating point formatting with 3 decimal places 32.600
            Right-aligned
       Also right-aligned
        Centered         
This is a formatted string that was formatted with literals.
My name is Nathaniel Stickley (Stickley@caltech.edu).
Error: an error message

Many more usage examples are given in the documentation here and here.

To download the library and install it, I suggest ignoring the instructions on the fmt website and GitHub (if you are running Linux, anyway). Here's a summary of what I did:

Then, when you compile a program that uses fmt, compile using the header-only library option, by setting FMT_HEADER_ONLY. I suggest this because you may encounter bugs if you try to compile the shared (dynamic) library. For example, to compile the program above, do this:

Alternatively, you can put format.h and format.cc in your source directory and #include "format.h" instead of fmt/format.h. Then compile with:

Of course, you may encounter no problems at all when using the shared library, so it's still worth a try.

Nathaniel R. Stickley
nrs@nrstickley.com
626-269-9830