c++stringformattingstring-formattingboost-format

Real positional string formatting?


(Note: I know of Boost.Format, I'm looking for a better way to do the following.)
First a use-case example: In some countries, you name a person by calling his / her surname first and the forename last, while in other countries it's the exact opposite.

Now, for my code, I currently solve this with Boost.Format in the following fashion:

#include <boost/format.hpp>
#include <iostream>
#include <stdlib.h>
#include <utility>

int main(){
    using namespace boost;

    int pos1 = 2, pos2 = 1;
    char const* surname = "Surname", *forename = "Forename";

    // decision on ordering here
    bool some_condition = false;

    if(some_condition)
      std::swap(pos1,pos2);

    char buf[64];
    sprintf(buf,"Hello %c%d%c %c%d%c",'%',pos1,'%','%',pos2,'%');
    // buf == "Hello %[pos1]% %[pos2]%"; with [posN] = value of posN

    std::cout << format(buf) % surname % forename;
}

Now, I would rather have it like this, i.e., everything in the format line:

std::cout << format("Hello %%1%% %%2%%") % pos1 % pos2 % surname % forename;

But sadly, that doesn't work, as I get a nice parsing exception.

Is there any library to have real positional formatting? Or even a way to achieve this with Boost.Format that I don't know of?


Solution

  • In my opinion, Boost.Spirit.Karma is the definitive modern output formatting library.