我想对一个数字进行零填充,使其具有 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);
演示
#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
因为它是用4个参数调用的
关于c++ - 如何使用 boost::format 对变量中包含小数位数的数字进行零填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27051585/