Using * Width & Precision Specifiers With boost :: format

I am trying to use width and precision specifiers with boost::formatfor example:

#include <boost\format.hpp>
#include <string>

int main()
{
    int n = 5;
    std::string s = (boost::format("%*.*s") % (n*2) % (n*2) % "Hello").str();
    return 0;
}

But this does not work because it boost::formatdoes not support the specifier *. Boost throws an exception when parsing a string.

Is there a way to achieve the same goal, preferably with a replacement replacement?

+5
source share
2 answers

Try the following:

#include <boost/format.hpp>
#include <iomanip>

using namespace std;
using namespace boost;

int main()
{
    int n = 5;
    string s = (format("%s") % io::group(setw(n*2), setprecision(n*2), "Hello")).str();
    return 0;
}

group () allows you to encapsulate one or more io manipulators with a parameter.

+8
source

Well, this is not a popup, but one way to do this would be to dynamically build a format string:

#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>

int main()
{
    int n = 5;
    const std::string f("%" + 
                        boost::lexical_cast<std::string>(n * 2) + "." +
                        boost::lexical_cast<std::string>(n * 2) + "s");
    std::string s = (boost::format(f) % "Hello").str();
}

, , .

boost::format() ; , , :

const std::string f = (boost::format("%%%d.%ds") % (n*2) % (n*2)).str();
std::string s = (boost::format(f) % "Hello").str();

( Ferruccio )

+2

All Articles