控制显示的位数c ++

时间:2017-03-07 12:05:49

标签: c++

我想显示这些特定寄存器和计数器的值(以十六进制表示),但我想限制显示的位数。

cout << "Acc register : " << hex << Acc << ",";      //display 2 digits
cout << " X register : " << hex << X << ",";         //display 3 digits
cout << " Program counter : " << hex << PC << ",";   //display 3 digits

如果值只有1位数,我还想显示前面的零,例如,如果是 program counter = 4

PC应显示为Program counter : 004

我在互联网上搜索试图找到解决方案,但我似乎找不到有用的东西。任何人都可以解释一下如何做到这一点。非常感谢。

1 个答案:

答案 0 :(得分:0)

STL附带一个名为iomanip的标题,它可以按你想要的方式修改,甚至更多。

一个简短的例子是:

#include <iomanip>
#include <iostream>

int main() {
    std::cout << std::setfill ('x');
    std::cout << "PC" << std::setw(3) << 4 << std::endl;
}

另外一个例子可以在这里找到: http://www.cplusplus.com/reference/iomanip/setfill/

此处所有选项的概述: http://www.cplusplus.com/reference/iomanip/