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

5

9

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?

Gerrard answered 27/2, 2011 at 2:33 Comment(2)
You do realize that anyone trying to read your hex numbers back in will see them as octal numbers? Just asking.:-)Defective
True, but this is for human consumption, not computer consumption.Gerrard
I
14

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

Incidental answered 27/2, 2011 at 2:42 Comment(0)
Q
2

This works:

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
  int x = 0x23;
  cout << "output: " << setfill('0') << setw(3) << hex << x << endl;
}

output: 023

Qoph answered 27/2, 2011 at 2:44 Comment(0)
S
1
glog << "Output: " << std::setfill('0') << std::hex(2) << int(myNum) << endl;

See also: http://www.arachnoid.com/cpptutor/student3.html

Stalwart answered 27/2, 2011 at 2:42 Comment(0)
D
1

Take a look at the setfill and setw manipulators in <iomanip>

Drawbar answered 27/2, 2011 at 2:42 Comment(0)
D
0

It is a little bit dirty, but a macro did a good job for me:

#define fhex(_v) std::setw(_v) << std::hex << std::setfill('0')

So then you can do it:

#include <iomanip>
#include <iostream>
...
int value = 0x12345;
cout << "My Hex Value = 0x" << fhex(8) << value << endl;

The output:

My Hex Value = 0x00012345

Differentiable answered 22/5, 2014 at 22:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.