【问题标题】:Copying format settings from one stream to another将格式设置从一个流复制到另一个
【发布时间】:2014-09-03 05:37:20
【问题描述】:

我正在为我的班级编写一个打印方法,例如:

std::ostream& operator<<(std::ostream& stream, const MyClass& M);

在里面我需要创建一个中间的stringstream,这样我以后把得到的字符串放到stream的正确位置。但stream 可能有一些非默认设置,如精度、字段宽度、数字格式等。

如何将所有这些格式设置从stream 复制到我的stringstream,而无需为每个设置手动执行“读取和设置”?

【问题讨论】:

    标签: c++ stream formatting


    【解决方案1】:

    您可以使用 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
    

    【讨论】:

      猜你喜欢
      • 2017-05-27
      • 2011-04-13
      • 2013-11-16
      • 1970-01-01
      • 2021-11-26
      • 2014-11-25
      • 1970-01-01
      • 2020-05-15
      相关资源
      最近更新 更多