Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to zero pre-fill for std::to_string function?

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.

like image 677
Chan Kim Avatar asked Nov 26 '18 06:11

Chan Kim


People also ask

What is to_ string in Cpp?

std::string to_string( long double value ); (9) (since C++11) Converts a numeric value to std::string. 1) Converts a signed integer to a string with the same content as what.

What library is To_string in C++?

C++ Bitset Library - to_string() Function.


2 Answers

ostringstream seems to be an overkill. You can simply insert the number of zeros you need:

template<typename T/*, typename = std::enable_if_t<std::is_integral_v<T>>*/>
std::string to_string_with_zero_padding(const T& value, std::size_t total_length)
{
    auto str = std::to_string(value);
    if (str.length() < total_length)
        str.insert(str.front() == '-' ? 1 : 0, total_length - str.length(), '0');
    return str;
}

This function also works correctly if the value is negative and/or if T is char or related type.

like image 82
Evg Avatar answered Oct 10 '22 17:10

Evg


Instead of using std::to_string(), you could use a std::ostringstream. The IO manipulators will work with a std::ostringstream.

#include <iostream>
#include <sstream>
#include <iomanip>

int main()
{
   for ( int i = 1; i <= 10; ++i )
   {
      std::ostringstream str;
      str << std::setw(3) << std::setfill('0') << i;
      std::cout << str.str() << std::endl;
   }
}

Output:

001
002
003
004
005
006
007
008
009
010

See it working at https://ideone.com/ay0Xzp.

like image 24
R Sahu Avatar answered Oct 10 '22 17:10

R Sahu