简体   繁体   English

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

[英]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: 现在我希望它始终打印一个前导零,如果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

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: 它不像我想的那么干净,但你可以将“填充”字符改为'0'来完成这项工作:

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(' '); 但请注意,您为填充设置的字符是“粘性”,因此在执行此操作后它将保持为“0”,直到您将其恢复到类似于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 输出:023

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

另见: http//www.arachnoid.com/cpptutor/student3.html

看看<iomanip>中的setfillsetw操纵器

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 我的十六进制值= 0x00012345

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM