在使用 std::to_string() 的 C++ 中,我应该如何预填充从整数转换的字符串?我尝试使用 #include 和 std::setfill('0') 但它不起作用。这是简单的测试代码。
#include <iostream>
#include <string>
//#include <iomanip> // setw, setfill below doesn't work
int main()
{
int i;
for (i=0;i<20;i++){
std::cout << "without zero fill : " << std::to_string(i) << ", with zero fill : " << std::to_string(i) << std::endl;
//std::cout << std::setw(3) << std::setfill('0') << "without zero fill : " << std::to_string(i) << ", with zero fill : " << std::to_string(i) << std::endl; // doesn't work
}
}
我想要做的是,将一些数字转换为字符串,但其中一些使用零填充,其他没有。(我实际上是用它来制作文件名。)我应该怎么做?
(我不知道为什么这不像在 C 中使用 %0d 或 %04d 格式说明符那么简单。)
ADD :从将前导零添加到字符串,没有 (s)printf,我发现
int number = 42;
int leading = 3; //6 at max
std::to_string(number*0.000001).substr(8-leading); //="042"
这对我有用,但我更喜欢更自然的解决方案,而不是这种类似技巧的方法。