重载ostream&operator<<:如何强制输出零?

Overloading ostream& operator<<: how to force outputting zeroes?

本文关键字:lt 输出 何强制 ostream 重载 operator      更新时间:2023-10-16

我想过载

ostream& operator<<(ostream& out, const myType& y)

以便输出在myType中由CCD_ 1的向量表示的大的无符号整数。因此,如果有问题的向量有元素1f, a356, 13d5,我想得到输出1fa35613d5——现在我只需要hexoct的输出。特别地,1, 0, 0应当被输出到100000000。我想通过连续输出向量的元素来实现这一点。然而,尽管我设置了,但我用这个方法得到的是100

out.width(4);
out.fill('0');
out << std::internal;
out << std::noskipws;

当然,我可以先将ushort写入字符串,然后输出,但我更喜欢只使用unsigned short0的格式化指令,因为这样可以更容易地遵守outhexoct设置。这里缺少哪个格式选项?

以下程序打印固定宽度的十六进制字符:

#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的状态保护程序。