A modern way to provide formatted strings as arguments

I have a question very similar to std :: string formatting, for example sprintf or this question , but it is very old, so I dare to try again to collect some approaches.

I want to have a function / method that takes arguments that define a formatted string with some variables, like printf/ sprintf. For example, it may be a method send_string(ARGS)that formats and sends a string to some receiver. For example:.

server->send_message("value1: %d, value2: %0.3f, value3: %s", 2, 3.14, "hello world");

I know the concept of flow, and I know boost::format. But I wonder what the smallest verbose approach is without extra dependencies.

Here's what comes to mind:

  • use a flow - based approach - the result will look like this:

    server->msg_out() << "value1: " << 2 
                      << ", value2: " << 3.14 
                      << ", value3: '" << "hello world" << "'";
    

    This view is the most plausible for me, but it is very detailed , it is difficult to understand how the conclusion will look. Especially when you are trying to get tabular output or special formatting for real values. On the plus side, you have no dependencies.

  • Use the arguments of a C based variable . It looks like the example above, which is well known and used a lot, although it is outdated, error prone and inflexible.

  • Use Boost.Format

    server->send_message(boost::format(
                "value1: %d, value2: %0.3f, value3: %s") % 2 % 3.14 % "hello world"));
    

    or (to avoid dependencies in your API):

    server->send_message(
        boost::str(
            boost::format(
                "value1: %d, value2: %0.3f, value3: %s") % 2 % 3.14 % "hello world")));
    

    , -, sprintf - ++. - , , , Boost ( ).

, , , , , : - !

, ?

+4
1

, Qt QString:: arg; %1... %9, arg , .

QString str;
long num;
double dbl;
QString outstr = 
 QString("str=%1 num=%2 dbl=%3").arg(str).arg(num).arg(dbl);

, arg, .

+3

Source: https://habr.com/ru/post/1622526/


All Articles