Using * Width & Precision Specifiers With boost::format

前端 未结 2 816
感动是毒
感动是毒 2020-12-18 06:51

I am trying to use width and precision specifiers with boost::format, like this:

#include 
#include 

int         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-18 07:17

    Well, this isn't a drop-in, but one way to do it would be to construct the format string dynamically:

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

    Of course, if you did this frequently, you could refactor construction of the format string into a function.

    You could also use boost::format() to generate the format string; it's shorter, but potentially less readable, especially for long format strings:

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

    (credit to Ferruccio for posting the second idea in the comments)

提交回复
热议问题