C++ Modern Formatting Library (cppformat) Setup

String formatting is a core need in whatever code you write. You always want your printed content should appear as intended and especially when printing stuff like date and time. If you use iostream you know how painful it is to format strings and so many still use printf.

Unfortunately printf comes with lot of problems, especially on the safety side. It’s very easy to get your format string wrong and although today modern compilers became good at catching those errors, they still let slip a couple because who doesn’t like 0-day.

Now if you have used python print formatting library, you might have wondered why can’t we have such a nice friendly library in c/c++.

Well good news guys 🙂 search ends for alternative of print formatting (printf/iostream/fastformat/boost formatting library in c++).

This post is about using a fast, safe and easy to use formatting library called C++ Format. This library is largely inspired from the str.format library of python and provides similar usage in c++. You only need to add two files, format.h and format.cc to your project in order to start using the library. And now C++ Format is available on major Linux distributions. This library also supports architectures like ARM, ppc64, ppc64le and s390x.

For more info watch this awesome talk from cppcon2017 by Victor Zverovich.

First you need to enable the Universe repository if you haven’t done it before:

sudo apt-add-repository universe && sudo apt-get update

Then you can install the library with apt-get:

sudo apt-get install libcppformat1-dev

To check that it works let’s create a small example (Now no need to write %d %s just put {} like python also it supports arg number):

// test.cpp
#include <cppformat/format.h>

int main() {
     fmt::print("Hello {1}!!! : {0}\n", 56, "World");

Compile and run it:

$ g++ test.cpp -std=c++11 -lcppformat -o test
$ ./test
Hello World!!! : 56



Join the Discussion

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: