Search code examples
c++formattingzeroclogleading-zero

What directive can I give a stream to print leading zeros on a number in C++?


I know how to cause it to be in hex:

unsigned char myNum = 0xA7;
clog << "Output: " std::hex << int(myNum) << endl;
// Gives:
//   Output: A7

Now I want it to always print a leading zero if myNum only requires one digit:

unsigned char myNum = 0x8;
// Pretend std::hex takes an argument to specify number of digits.
clog << "Output: " << std::hex(2) << int(myNum) << endl;
// Desired:
//   Output: 08

So how can I actually do this?


Solution

  • It's not as clean as I'd like, but you can change the "fill" character to a '0' to do the job:

    your_stream << std::setw(2) << std::hex << std::setfill('0') << x;
    

    Note, however, that the character you set for the fill is "sticky", so it'll stay '0' after doing this until you restore it to a space with something like your_stream << std::setfill(' ');.