What directive can I give a stream to print leading zeros on a number in C++?
I know how to cause i开发者_C百科t 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?
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(' ');
.
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
glog << "Output: " << std::setfill('0') << std::hex(2) << int(myNum) << endl;
See also: http://www.arachnoid.com/cpptutor/student3.html
Take a look at the setfill
and setw
manipulators in <iomanip>
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
精彩评论