Real formatting of a position line?

(Note: I know Boost.Format, Iโ€™m looking for a better way to do the following.)
First, an example of use: in some countries you name a person, first telling your last name, and the file name is the last, and in other countries the opposite.

Now, for my code, I am currently solving this using Boost.Format as follows:

#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 prefer it this way, that is, everything in the line format:

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

But unfortunately this does not work as I get a nice parsing exception.

Is there any library for real positional formatting? Or even a way to achieve this with Boost.Format, which I don't know about?

+3
source
6
+1

Boost.Locale, GNU gettext.

:

cout << format(translate("Hello {1} {2}!")) % forename % surname << endl;

, :

msgid "Hello {1} {2}!"
msgstr "ใ“ใ‚“ใซใกใฏ {2}-ใ•ใ‚“!"
+1

,

std::swap(surname, forename)

. , :

const std::string& param1(bSwapThem? forename : surname);
const std::string& param2(bSwapThem? surname  : forename);

0

, , , .

?

   if(some_condition)
      std::cout << surname << " " << forename;
   else
      std::cout << forename << " " << surname;
0

?:

char const* surname = "Surname", *forename = "Forename";
bool swapFlag = (some_condition) ? true : false;

std::cout << "Hello " << (swapFlag ? surname : forename) << " " << (!swapFlag ? surname : forename) << std::endl;
0

, :

cout << format(str(format("%%%1%%% %%%2%%%") % pos1 % pos2)) % surname % forname;

- GNU gettext.

0

All Articles