Tech News
← Back to articles

A string formatting library in 65 lines of C++

read original related products more articles

In this write-up, I will walk you through an implementation of a string formatting library for C++ I came up with for my video game. The end result came out really compact, at only 65 lines of code—providing a skeleton that can be supplemented with additional functionality at low cost.

Usage

Given a format buffer…

char buffer [ 64 ] ; String_Buffer buf = { str , sizeof str } ;

…the fmt::format function provided by this library can be called with a format string parameter, containing the character sequence {} (a hole) where parameters are to be substituted, as well as the parameters themselves.

fmt :: format ( buf , "Hello, {}!" , "world" ) ; assert ( strcmp ( str , "Hello, world!" ) == 0 ) ;

When a literal {{ is needed, the { must be doubled—even when format arguments are not present.

fmt :: format ( buf , "Hello, {{}!" ) ; assert ( strcmp ( str , "Hello, {}!" ) == 0 ) ;

Further, when a format argument is not present, no undefined behaviour occurs—the hole is rendered as the empty string.

fmt :: format ( buf , "empty {} hole" ) ; assert ( strcmp ( str , "empty hole" ) == 0 ) ;

... continue reading