【问题标题】:Switching between different numeric formatting styles in an iostream在 iostream 中的不同数字格式样式之间切换
【发布时间】:2014-03-24 22:39:26
【问题描述】:

我有一个 C++ 程序将输出写入iostream,但是我需要经常在不同的数字样式之间切换,例如科学与非科学之间。这是我正在查看的内容:

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    cout << setw(2) << 1 << ' ' << setw(4) << 0.25 << ' ';
    cout.width(6);
    cout.setf(ios::scientific, ios::floatfield);
    cout << 3.0 << ' ';
    cout.unsetf(ios::floatfield);
    cout << 4.0 << ' ';
    cout.setf(ios::scientific, ios::floatfield);
    cout << 3.0 << ' ';
    cout.unsetf(ios::floatfield);
    cout << 4.0 << endl;
    return 0;
}

这种荒谬是必要的吗?看起来很可怕。作为比较,这在 C 语言中看起来更加合理:

#include <stdio.h>

int main()
{
    printf("%2d %4g %6e %6g %6e %6g\n", 1, 0.25, 3.0, 4.0, 3.0, 4.0);
    return 0;
}

有什么方法可以在 C++ 中使用iostream 使其更易于阅读?

【问题讨论】:

    标签: c++ iostream number-formatting scientific-notation


    【解决方案1】:

    这也可能是矫枉过正,但您可以实现一些轻量级类型,为您进行自定义格式

    struct Scientific
    {
      double value;
      Scientific(double value) : value(value) { } 
    };
    
    ostream& operator<< (ostream &o, const Scientific& p) {
      o.setf(ios::scientific, ios::floatfield);
      o << p.value;
      o.unsetf(ios::floatfield);
      return o;
    }
    

    那么科学记数法可以指定为值的注释而不是多行

    cout << 1 << ' ' << Scientific(2.0) << ' ' << endl;
    

    【讨论】:

      【解决方案2】:

      另一种方法是使用宏:

      #include <iostream>
      #include <iomanip>
      
      using std::hex;
      using std::scientific;
      using std::cout;
      using std::endl;
      
      define H hex
      define S scientific
      
      int main(int argc, char **argv) {
        cout << H << 10 << S << 10 << endl;
      
        return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-03
        • 2018-12-21
        • 2018-05-26
        • 2019-10-17
        • 1970-01-01
        相关资源
        最近更新 更多