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

3

12

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

}
Venipuncture answered 2/3, 2010 at 19:30 Comment(0)
D
13

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
Desultory answered 2/3, 2010 at 19:35 Comment(3)
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?Venipuncture
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!Desultory
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.Desultory
I
3

I would use:

cout << std::hex << std::setw(sizeof(i)*2) << std::setfill('0') << i << std::endl;
Iceskate answered 2/3, 2010 at 19:40 Comment(2)
Can't you just say std::setw(8)? After all, that's what the OP says he wants.Itin
@Kristo Oh, yeah, setw(8) would be fine, I overlooked that he wants always 8 characters. This will work with bit size.Altair
H
1

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    
}
Hasan answered 2/3, 2010 at 19:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.