C++ 如何使用boost::format将变量中包含小数位数的数字归零?

C++ 如何使用boost::format将变量中包含小数位数的数字归零?,c++,boost,zero-pad,boost-format,C++,Boost,Zero Pad,Boost Format,我想对一个数字进行零填充,使其具有5位数字,并将其作为字符串。这可以通过以下方式完成: unsigned int theNumber = 10; std::string theZeropaddedString = (boost::format("%05u") % theNumber).str(); 但是,我不想硬编码位数(即“%05u”中的5) 如何使用boost::format,但通过变量指定位数 (即,将位数放入unsigned int numberOfDigits=5中,然后将numbe

我想对一个数字进行零填充,使其具有5位数字,并将其作为字符串。这可以通过以下方式完成:

unsigned int theNumber = 10;
std::string theZeropaddedString = (boost::format("%05u") % theNumber).str();
但是,我不想硬编码位数(即“%05u”中的5)

如何使用boost::format,但通过变量指定位数


(即,将位数放入
unsigned int numberOfDigits=5
中,然后将numberOfDigits与boost::format一起使用)

也许您可以使用标准io操纵器修改格式化程序项:

int n = 5; // or something else

format fmt("%u");
fmt.modify_item(1, group(setw(n), setfill('0'))); 
对于给定的格式,您还可以添加该内联:

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

因为它是用4个参数调用的

谢谢。太好了。在我接受它作为答案之前,我会给它多一点时间,因为我想看看其他人是否也有好的答案。好问题,好答案。不知道为什么选票这么少。
#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);
}
0042