Chris Redford
Chris Redford

Reputation: 17788

C++11 Equivalent to Boost.Format

Anything like Boost.Format in the C++11 standard? I've been able to avoid using Boost with a better C++11 option for every other need I've had.

For that matter, Boost.Format doesn't hold a candle to the syntax of Python format(). Something like that would be even better.

Upvotes: 26

Views: 16795

Answers (5)

Alen Wesker
Alen Wesker

Reputation: 245

template<typename... Args>
std::string fmt_str(const std::string& fmt, Args... args)
{
    static const int bufferSize = 1000;
    char buffer[bufferSize];
    int n = snprintf(buffer, bufferSize, fmt.c_str(), args...);
    assert(n >= 0 and n <= bufferSize - 1 && "check fmt_str output");

    return (buffer);
}

//Based on Markus, a little improvements: input change to ref, buffer avoid new, use snprintf to avoid buffer overflow, return directly to avoid copy constructor. Using it in my project

//It should be a comment to Markus Dutschke's, not an answer, but the comment field can't format a code piece well, and I extract the code here.

Upvotes: 0

galarius
galarius

Reputation: 118

Python-like format string function implementation with c++11 regex and variadic templates.

/**
   Helper code to unpack variadic arguments
*/
namespace internal
{
    template<typename T>
    void unpack(std::vector<std::string> &vbuf, T t)
    {
        std::stringstream buf;
        buf << t;
        vbuf.push_back(buf.str());
    }
    template<typename T, typename ...Args>
    void unpack(std::vector<std::string> &vbuf, T t, Args &&... args)
    {
        std::stringstream buf;
        buf << t;
        vbuf.push_back(buf.str());
        unpack(vbuf, std::forward<Args>(args)...);
    }
}

/**
    Python-like string formatting
 */
template<typename ... Args>
std::string format(const std::string& fmt, Args ... args)
{
    std::vector<std::string> vbuf;  // store arguments as strings
    std::string in(fmt), out;    // unformatted and formatted strings
    std::regex re_arg("\\{\\b\\d+\\b\\}");  // search for {0}, {1}, ...
    std::regex re_idx("\\b\\d+\\b");        // search for 0, 1, ...
    std::smatch m_arg, m_idx;               // store matches
    size_t idx = 0;                         // index of argument inside {...}

    // Unpack arguments and store them in vbuf
    internal::unpack(vbuf, std::forward<Args>(args)...);

    // Replace all {x} with vbuf[x]
    while (std::regex_search(in, m_arg, re_arg)) {
        out += m_arg.prefix();
        auto text = m_arg[0].str();
        if (std::regex_search(text, m_idx, re_idx)) {
            idx = std::stoi(m_idx[0].str());
        }
        if(idx < vbuf.size()) {
            out += std::regex_replace(m_arg[0].str(), re_arg, vbuf[idx]);
        }
        in = m_arg.suffix();
    }
    out += in;
    return out;
}

Example: cpp.sh/9cvtz

Upvotes: 2

Markus Dutschke
Markus Dutschke

Reputation: 10606

using sprintf

  • For C++20, use std::format
  • there is the fmt-library from version C++11 on
  • some simple solution for formated output is printf
  • to use printf syntax to write a std::string, use the following snippet

minimal reproducible example: format std::string with printf syntax

interactive version

#include <iostream>
#include <string>
#include <stdio.h>
#include <assert.h>


template<typename... Args>
std::string fmt_str(std::string fmt, Args... args)
{
    size_t bufferSize = 1000;
    char *buffer = new char[bufferSize];
    int n = sprintf(buffer, fmt.c_str(), args...);
    assert (n >= 0 and n < (int) bufferSize - 1  && "check fmt_str output");

    std::string fmtStr (buffer);
    delete buffer;
    return fmtStr;
}



int main()
{
    int a=1, b=2;
    double c=3.;
    std::cout << fmt_str("%d plus %d is %f", a, b, c) << std::endl;
    return 0;
}

output

1 plus 2 is 3.000000

Upvotes: 0

vitaut
vitaut

Reputation: 55625

C++11, 14 and 17 don't provide anything like that.

However, C++20 provides std::format which is similar in spirit to Boost Format but with the design permitting more efficient implementation. The {fmt} library is an implementation of this formatting facility and it only requires C++11:

std::string s = fmt::format("I'd rather be {1} than {0}.", "right", "happy");

Disclaimer: I'm the author of {fmt} and C++20 std::format

Upvotes: 33

nosid
nosid

Reputation: 50094

There is a proposal for something similar to boost-format. However, it's neither part of C++11 nor C++14, nor has anything related to string formatting be added.

Here you can find the latest proposal. In contrast to boost-format, it's based on variadic templates.

Upvotes: 7

Related Questions