我想重载
ostream& operator<<(ostream& out, const myType& y)
为了输出 myType 中由 unsigned Short
vector 表示的大无符号整数。因此,如果所讨论的 vector 具有元素 1f, a356, 13d5
我想获得输出 1fa35613d5
——现在我只需要这个 十六进制
或八进制
输出。
特别是,1, 0, 0
应输出为100000000
。我想通过连续输出 vector 的元素来实现这一点。然而,我用这个方法得到的是 100
,尽管我设置了
out.width(4);
out.fill('0');
out << std::internal;
out << std::noskipws;
当然,我可以先将ushort
写入字符串,然后输出它,但我更愿意只使用out
的格式化指令,因为这样更容易遵守 out
的 hex
或 oct
设置。我在这里缺少哪个格式选项?
最佳答案
以下程序打印固定宽度的十六进制字符:
#include <iostream>
#include <iomanip>
#include <vector>
int main()
{
std::vector<unsigned short int> v { 10, 25, 0, 2000 };
for (auto n : v)
{
std::cout << "0x" << std::hex << std::setfill('0')
<< std::setw(4) << n << std::endl;
}
}
输出:
0x000a
0x0019
0x0000
0x07d0
如果您为此编写格式化函数,则不必重复 std::hex
,因为这是永久性的。不过,保留 ostream 的状态有点棘手,所以也许您应该研究一下 Boost 的状态保护程序之类的东西。
关于c++ - 重载ostream&运算符<< : how to force outputting zeroes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9250775/