user3731622
user3731622

Reputation: 5095

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)

Upvotes: 5

Views: 4445

Answers (2)

kwarnke
kwarnke

Reputation: 1514

You can build the format string with boost::format too ('''%%0%uu''' expands to '''%5u'''):

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

using namespace boost;

int main(int argc, char const**) {
  unsigned int theNumber = 10;
  unsigned int numberOfDigits = 5;
  std::string fmtStr = (boost::format("%%0%uu") % numberOfDigits).str();
  std::string theZeropaddedString = (boost::format(fmtStr) % theNumber).str();
  std::cout << theZeropaddedString << std::endl; // 00010
}

Live demo

Upvotes: 0

sehe
sehe

Reputation: 392999

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

Upvotes: 2

Related Questions