2

I need to display three values which is parsed from packet binary data(0x123400005678).

unsigned int k = 0x1234, l=0x0, m=0x5678;

I can display with four-digit hex value when I use cout three times.

#include <iostream>
#include <iomanip>
...
cout << "seperated cout" << endl;
cout << hex << setfill ('0') << setw (4) << k;
cout << hex << setfill ('0') << setw (4) << l;
cout << hex << setfill ('0') << setw (4) << m << endl;
....

seperated cout
123400005678

But when I use only one cout line, leading zero of '0x0' is omitted...

#include <iostream>
#include <iomanip>
...
cout << "oneline cout" << endl;
cout << hex << setfill ('0') << setw (4) << k << l << m << endl;
...

oneline cout
123405678

Is there anyway to display like '123400005678' with one line cout? Or is using cout three times only way to do this?

Thank you in advance.

simryang
  • 80
  • 8
  • 1
    Ultimately the answer for you will be provided here: ["Which io manipulators are sticky?"](https://stackoverflow.com/questions/1532640/which-iomanip-manipulators-are-sticky). The short of it is, `std::setw` only affects the *next* output datum. The linked question dives in to considerably more than that, discussing *all* manipulators and their sticky-or-not effects. – WhozCraig Jun 01 '15 at 05:07
  • Thank @WhozCraig . It is helpful to understand the 'sticky' of manipulators. – simryang Jun 01 '15 at 06:46

1 Answers1

3

Field width isn't "sticky", so you need to set it again for each field you print out:

cout << hex << setfill ('0') << setw (4) << k << setw(4) << l << setw(4) << m << endl;

Result:

123400005678

The fill character is sticky though, so you usually want to set it back to a space character as soon as you're done using whatever other value you set:

cout << setfill(' ');
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111