How do I use a manipulator to format my hex output with padded left zeros

bbazso picture bbazso · Mar 2, 2010 · Viewed 10.3k times · Source

The little test program below prints out:

And SS Number IS =3039

I would like the number to print out with padded left zeros such that the total length is 8. So:

And SS Number IS =00003039 (notice the extra zeros left padded)

And I would like to know how to do this using manipulators and a stringstream as shown below. Thanks!

The test program:

#include <iostream>
#include <sstream>
#include <string>
#include <vector>

int main()
{

    int i = 12345;
    std::stringstream lTransport;

    lTransport << "And SS Number IS =" << std::hex << i << '\n';

    std::cout << lTransport.str();

}

Answer

Dr. Watson picture Dr. Watson · Mar 2, 2010

Have you looked at the library's setfill and setw manipulators?

#include <iomanip>
...
lTransport << "And SS Number IS =" << std::hex << std::setw(8) ;
lTransport << std::setfill('0') << i << '\n';

The output I get is:

And SS Number IS =00003039