重载ostream&operator<<:如何强制输出零?
Overloading ostream& operator<<: how to force outputting zeroes?
我想过载
ostream& operator<<(ostream& out, const myType& y)
以便输出在myType中由CCD_ 1的向量表示的大的无符号整数。因此,如果有问题的向量有元素1f, a356, 13d5
,我想得到输出1fa35613d5
——现在我只需要hex
或oct
的输出。特别地,1, 0, 0
应当被输出到100000000
。我想通过连续输出向量的元素来实现这一点。然而,尽管我设置了,但我用这个方法得到的是100
out.width(4);
out.fill('0');
out << std::internal;
out << std::noskipws;
当然,我可以先将ushort
写入字符串,然后输出,但我更喜欢只使用unsigned short
0的格式化指令,因为这样可以更容易地遵守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++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 呼叫运营商<<临时
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- 过载输出<<用于类的运算符,以打印其中的元组
- 重载运算符<<输出地址而不是数据成员
- 什么会导致死亡<<变量& lt; & lt;“ t";当输出超过终端宽度时,打印空白而不是值
- Can运算符<<用于设计我们自己的输出显示方式