c++ - 如何使用 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,然后将 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);

演示

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);
}

打印的地方

0042

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

关于c++ - 如何使用 boost::format 对变量中包含小数位数的数字进行零填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27051585/

相关文章:

java - 在 Java 中对微调器进行零填充

c++ - 停止小数点前的双除法(低精度,快速除法;只得到 'quotient' )

c++ - 生成随机数 - srand c++

c++ - OpenCL 编译器异常情况

NetBSD '::system' 上的 C++ 编译错误尚未声明

c++ - 私有(private)继承出现 "an inaccessible base"错误

c++ - 无法完成构建 cgal sln

c++ - 是否有必要释放 shared_ptr?

php - 在 PHP 中,如何添加到零填充数字字符串并保留零填充?