What directive can I give a stream for printing leading zeros on a number in C ++?

I know how to make it be in hexadecimal format:

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

Now I want it to always print leading zero if myNum requires only 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 do this?

+8
c ++ formatting zero
source share
5 answers

This is not as clean as we would like, but you can change the fill symbol to 0 to complete the task:

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

Note, however, that the character you set to fill is β€œsticky,” so after that it will remain β€œ0” until you restore it to a place with something like your_stream << std::setfill(' '); .

+13
source share

It works:

 #include <iostream> #include <iomanip> using namespace std; int main() { int x = 0x23; cout << "output: " << setfill('0') << setw(3) << hex << x << endl; } 

output: 023

+2
source share
 glog << "Output: " << std::setfill('0') << std::hex(2) << int(myNum) << endl; 

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

+1
source share

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

+1
source share

This is a bit dirty, but the macro did a good job for me:

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

So you can do this:

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

Exit:

My Hex Value = 0x00012345

0
source share

All Articles