【问题标题】:Non-persistent formatting of streams流的非持久格式
【发布时间】:2015-11-05 10:50:03
【问题描述】:

以本地化方式格式化std::*stream 输出的最佳方式(如果有)是什么,这样一个位置的格式更改不会影响在其他位置使用该流?

也就是说,我想为单个语句设置流的格式,而不是为流的剩余生命周期设置。


以下只是提出上述问题的理由。

假设您以默认浮点格式打印强度:

ostringstream oss;
oss << "Intensity = " << intensity << "; ";

然后以固定的 2 位精度打印坐标:

oss << "Point = (" << fixed << setprecision(2) << pt.x << ", " << pt.y << "); ";

然后,20 行之后,以相同的固定 2 位格式打印光线方向:

oss << "Direction = (" << dir.x << ", " << dir.y << "); ";

几个月后,在打印pt和打印dir之间的某处添加默认浮点格式的亮度打印:

oss << "Luminosity = " << lum << "; ";

糟糕,lum 将以固定的 2 位精度打印,因为您之前在打印 pt 时更改了 oss 格式 20 行。现在您必须回忆您在oss 中所做的更改,然后将其倒回以打印lum。 此外,在为lum 修复格式后,您会遇到另一个问题:dir 将不再以固定的 2 位数字打印...

因此,我希望能够在本地格式化流以避免不必要的依赖。

【问题讨论】:

    标签: c++ stream format output


    【解决方案1】:

    您可以简单地保存和恢复流格式标志(参见std::iosbase::flags()):

    fmtflags oldflags = oss.flags();
    
    // change current format flags
    
    oss.flags(oldflags); // <<< restore to former state
    

    如果你不喜欢上面提到的直接,你也可以使用代理:

    class local_ostream {
    public:
        friend template<typename T> 
        local_ostream& operator<<(local_ostream& los, const& T value) {
            los.os_ << value;
            return los;
        }
    
        local_ostream(std::ostream& os) : os_(os), oldflags_(os.flags()) {
        }
        ~local_ostream() {
           os_.flags(oldflags_);
        }      
    
    private:
        std::ostream& os_;
        std::iosbase::fmtflags oldflags_;
    };
    

    并按如下方式使用:

     { local_ostream los(oss);
         los << "Point = (" << fixed << setprecision(2) << pt.x << ", " << pt.y << "); ";
     } // previous formatting state is restored here
    

    【讨论】:

      猜你喜欢
      • 2016-11-04
      • 2017-07-12
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-29
      • 2018-08-08
      • 2023-03-24
      相关资源
      最近更新 更多