【问题标题】:using setw with user-defined ostream operators将 setw 与用户定义的 ostream 运算符一起使用
【发布时间】:2011-01-15 23:33:20
【问题描述】:

如何使 setw 或类似的东西(增强格式?)与我的用户定义的 ostream 运算符一起使用? setw 仅适用于推送到流中的下一个元素。

例如:

cout << "    approx: " << setw(10) << myX;

myX 属于 X 类型,我有自己的

ostream& operator<<(ostream& os, const X &g) {
    return os << "(" << g.a() << ", " << g.b() << ")";
}

【问题讨论】:

    标签: c++ boost stream


    【解决方案1】:

    只需确保您的所有输出都作为对operator&lt;&lt; 的同一调用的一部分发送到流。实现此目的的一种直接方法是使用辅助ostringstream 对象:

    #include <sstream>
    
    ostream& operator<<(ostream& os, const X & g) {
    
        ostringstream oss;
        oss << "(" << g.a() << ", " << g.b() << ")";
        return os << oss.str();
    }  
    

    【讨论】:

      【解决方案2】:

      使用width 函数可能是这样:

      ostream& operator<<(ostream& os, const X &g) {
          int w = os.width();
          return os << "(" << setw(w) << g.a() << ", " << setw(w) << g.b() << ")";
      }
      

      【讨论】:

      • 这样总宽度是 w 的 3 倍,各个项目之间的空白太多了。
      • 使用 os.width() 你应该能够自己修复它。
      猜你喜欢
      • 2022-11-15
      • 2022-07-04
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多