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

}
Cœur
  • 37,241
  • 25
  • 195
  • 267
bbazso
  • 1,959
  • 6
  • 22
  • 30

3 Answers3

12

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
  • 3,752
  • 4
  • 32
  • 43
  • 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 Mar 02 '10 at 19:39
  • 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 Mar 02 '10 at 19:43
  • 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 Mar 02 '10 at 19:48
3

I would use:

cout << std::hex << std::setw(sizeof(i)*2) << std::setfill('0') << i << std::endl;
Šimon Tóth
  • 35,456
  • 20
  • 106
  • 151
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    
}
codaddict
  • 445,704
  • 82
  • 492
  • 529