5

I understand that you can use iomanip to set a precision flags for floats (e.g. have 2.0000 as opposed to 2.00).

Is there a way possible to do this, for integers?

I would like a hex number to display as 000e8a00 rather than just e8a00 or 00000000 rather than 0.

Is this possible in C++, using the standard libraries?

Anthony
  • 53
  • 2

2 Answers2

7

With manipulators:

std::cout << std::setfill('0') << std::setw(8) << std::hex << 0 << std::endl;

Without manipulators:

std::cout.fill('0');
std::cout.width(8);
std::cout.setf(std::ios::hex, std::ios::basefield);
std::cout << 42 << std::endl;
Nick Meyer
  • 39,212
  • 14
  • 67
  • 75
5

You can also do this with boost::format, which I find often saves typing:

std::cout << boost::format("%08x\n") % 0xe8a00;

It also allows for some nice code reuse, if you have multiple places you need to do the same formatting:

boost::format hex08("%08x");
std::cout << hex08 % 0xe8aa << std::endl;
swestrup
  • 4,079
  • 3
  • 22
  • 33