4

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)

user3731622
  • 4,844
  • 8
  • 45
  • 84

1 Answers1

2

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

sehe
  • 374,641
  • 47
  • 450
  • 633
  • 1
    Thanks. That's great. I'll give it a little more time before I accept it as an answer because I'd like to see if other people might also have good answers. – user3731622 Nov 21 '14 at 00:55
  • Nice question and great answer. Wonder why there are so little votes. – Zhang May 16 '21 at 03:38