c++boostzero-padboost-format

How to use boost::format to zeropad a number where the number of decimal places is contained in a variable?


I would like to zeropad a number such that it has 5 digits and get it as a string. This can be done with the following:

unsigned int theNumber = 10;
std::string theZeropaddedString = (boost::format("%05u") % theNumber).str();

However, I do not want to hardcode the number of digits (i.e. the 5 in "%05u").

How can I use boost::format, but specify the number of digits via a variable?

(i.e. put the number of digits in unsigned int numberOfDigits = 5 and then use numberOfDigits with boost::format)


Solution

  • Maybe you can modify the formatter items using standard io manipulators:

    int n = 5; // or something else
    
    format fmt("%u");
    fmt.modify_item(1, group(setw(n), setfill('0'))); 
    

    With a given format, you can also add that inline:

    std::cout << format("%u") % group(std::setw(n), std::setfill('0'), 42);
    

    DEMO

    Live On Coliru

    #include <boost/format.hpp>
    #include <boost/format/group.hpp>
    #include <iostream>
    #include <iomanip>
    
    using namespace boost;
    
    int main(int argc, char const**) {
        std::cout << format("%u") % io::group(std::setw(argc-1), std::setfill('0'), 42);
    }
    

    Where it prints

    0042
    

    because it is invoked with 4 parameters