views:

57

answers:

3

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

}
+4  A: 

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
Dr. Watson
If I am adding stuff before and after the formatted hex, how do the fill and width affect things? Is there a way for them to only apply to the formatted hex and not the whole stringstream?
bbazso
I edited my answer to add the code. I hope it will work for you. Oh! Looks like "Let_Me_Be" beat me to it!
Dr. Watson
After setting the formatters and writing to the stringstreamm for the integer, you can readjust the setw() and setfill() as you like. Alternatively, you could also pre-format a c-string using sprintf(char_buf, '%08X',i) and write that to the stringstream.
Dr. Watson
A: 

I would use:

cout << std::hex << std::setw(sizeof(i)*2) << std::setfill('0') << i << std::endl;
Let_Me_Be
Can't you just say `std::setw(8)`? After all, that's what the OP says he wants.
Kristo
@Kristo Oh, yeah, setw(8) would be fine, I overlooked that he wants always 8 characters. This will work with bit size.
Let_Me_Be
+1  A: 

You can use setw and setfill functions as follows:

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

using namespace std;

int main()
{    
    int i = 12345;
    std::stringstream lTransport;

    lTransport << "And SS Number IS =" << setfill ('0') << setw (8)<< std::hex << i << '\n';    
    std::cout << lTransport.str();  // prints And SS Number IS =00003039    
}
codaddict