正在将格式设置从一个流复制到另一个流
Copying format settings from one stream to another
我正在为我的类编写一个打印方法,比如:
std::ostream& operator<<(std::ostream& stream, const MyClass& M);
在内部,我需要创建一个中间stringstream
,以便稍后将我得到的字符串放在stream
中的正确位置。但stream
可能有一些非默认设置,如精度、字段宽度、数字格式等
如何将所有此类格式设置从stream
复制到我的stringstream
,而无需手动对每个设置进行"读取和设置"?
您可以使用copyfmt()将格式选项从一个流复制到另一个流:
std::ostream& operator<<(std::ostream& stream, const MyClass& M) {
std::ostringstream tmp; // temporary string stream
tmp.copyfmt(stream); // COPY FORMAT of origninal stream
... // rest of your code
}
一次复制所有格式选项,例如:
MyClass o;
...
std::cout.fill('*');
std::cout.width(10);
std::cout << o<<std::endl; // stringstream rendering would use fill and width here
std::cout << std::hex << o << std::dec <<std::endl; // and even hex conversion here
相关文章:
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 矢量如何将数据复制到另一个矢量?
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- 链表,将列表复制到另一个列表
- 关于复制构造函数的一个棘手问题
- 将指向给定子类的指针从一个向量复制到另一个向量
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 为什么 std::map emplace 需要在 gcc 上有一个复制构造函数
- C++使用默认的复制构造函数,即使用户使用模板定义了一个复制构造函数
- Rcpp 需要一个复制构造函数
- 你能为具有常量成员的联合编写一个复制构造函数吗?
- 需要一个复制构造函数
- 如何从点赞列表中创建一个复制构造函数
- 返回值优化是否需要声明一个复制构造函数
- 给出两个二进制数,将一个子集从一个复制到另一个
- 是否应该为具有指向其父对象的指针的对象定义一个复制构造函数
- 为什么不是只有一个?复制构造函数和赋值操作符
- 为什么编译器需要一个复制构造函数,需要并移动一个并且不使用它们中的任何一个?
- 另一个复制算法
- 创建一个复制构造函数,该构造函数对输入对象进行深度复制(使用数组)