In C++ using std::to_string(), how should I pre-fill a string converted from integer? I tried using #include and std::setfill('0') but it didn't work. here's the simple test code.
#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
}
}
What I want to do is, to have some numbers converted into string, but some of them with zero padding, the others not.(I'm using it to make filename actually.) How should I do it?
(I don't know why this should be not so simple as in C using %0d or %04d format specifier.)
ADD : From Add leading zero's to string, without (s)printf, I found
int number = 42;
int leading = 3; //6 at max
std::to_string(number*0.000001).substr(8-leading); //="042"
This works for me, but I'd prefer more natural solution, than this trick like method.