我可以使用什么指令为C ++中的数字打印前导零?

我知道如何使它成十六进制:
unsigned char myNum = 0xA7;
clog << "Output: " std::hex << int(myNum) << endl;
// Gives:
//   Output: A7
现在我希望它始终打印一个前导零,如果myNum只需要一个数字:
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
那我该怎么做呢?     
已邀请:
它不像我想的那么干净,但你可以将“填充”字符改为'0'来完成这项工作:
your_stream << std::setw(2) << std::hex << std::setfill('0') << x;
但请注意,您为填充设置的字符是“粘性”,因此在执行此操作后它将保持为“0”,直到您将其恢复到类似
your_stream << std::setfill(' ');
的空间。     
这有效:
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
  int x = 0x23;
  cout << "output: " << setfill('0') << setw(3) << hex << x << endl;
}
输出:023     
glog << "Output: " << std::setfill('0') << std::hex(2) << int(myNum) << endl;
另见:http://www.arachnoid.com/cpptutor/student3.html     
看看&lt; iomanip>中的
setfill
setw
操纵器     
它有点脏,但宏对我来说做得很好:
#define fhex(_v) std::setw(_v) << std::hex << std::setfill('0')
那么你可以这样做:
#include <iomanip>
#include <iostream>
...
int value = 0x12345;
cout << "My Hex Value = 0x" << fhex(8) << value << endl;
输出:   我的十六进制值= 0x00012345     

要回复问题请先登录注册