How to use boost :: format to enumerate a number that contains the number of decimal places in a variable?
I would like to zero out the number so that it has 5 digits and gets it as a string. This can be done as follows:
unsigned int theNumber = 10;
std::string theZeropaddedString = (boost::format("%05u") % theNumber).str();
However, I don't want to hardcode the number of digits (ie 5 in "% 05u").
How can I use boost :: format but specify the number of digits through a variable?
(i.e. unsigned int numberOfDigits = 5
put the number of digits in and then use numberOfDigits with boost :: format)
+3
source to share
1 answer
Perhaps you can change the formatting elements using the standard io handles:
int n = 5; // or something else
format fmt("%u");
fmt.modify_item(1, group(setw(n), setfill('0')));
In this format, you can also add that inline:
std::cout << format("%u") % group(std::setw(n), std::setfill('0'), 42);
DEMO
#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 does he print
0042
since it is called with 4 parameters
+1
source to share