C++输出对齐和小数位数保持器

C++ output align and decimal place holder?

本文关键字:小数 输出 对齐 C++      更新时间:2023-10-16

嗨,我有一个小问题。
我正在做我的C++作业,样本输出是

% cat this.out
  5.00       0.00 
  1.55       4.76 
 -4.05       2.94 
 -4.05      -2.94 
  1.55      -4.76 

但我得到的是

% cat test.out
    5       0
    1.55    4.76
    -4.05   2.94
    -4.05   -2.94
    1.55    -4.76

我不知道如何使我的输出格式看起来像那样。在这种情况下,我遇到的另一个问题是,我希望输出中的第一行类似于5.00 0.00,但即使我设置了precision(3) ,它也不起作用

这是我的代码生成的输出,请看一下。

file.open (filename, fstream :: in | fstream :: trunc);
    if(!file.is_open())
    {
            cerr << "Error opening file " << filename << endl;
            cout << "Exiting..." << endl;
            exit(0);
    }
    for(i = 0 ; i < num; i ++)
    {
            angle = 2 * M_PI * i/num;
            x = rad * cos(angle);
            y = rad * sin(angle);
            file.precision(3);
            // x, y are double
            file << "t" << x << "t" << y << endl;
    }
    cout << "finished";
    file.close();

您需要在标准库头<iomanip>中查找输入/输出操纵器

这些是内联使用的,如:

std::cout << "t" << std::fixed << std::setprecision(z) << x

你最感兴趣的是:

  • std::fixed
  • std::setprecision
  • std::setw

这应该可以做到:

file.precision(2);
file << fixed << "t" << x << "t" << y << endl;  

通常,您需要为特定语义定义一个操纵器。为了快速工作,我经常使用一个类似于的

class FFmt
{
    int myWidth;
    int myPrecision:
public:
    FFmt( int width, int precision )
        : myWidth( width )
        , myPrecision( precision )
    {
    }
    friend std::ostream& 
    operator<<( std::ostream& dest, FFmt const& format )
    {
        dest.setf( std::ios_base::fixed, std::ios_base::floatfield );
        dest.precision( myPrecision );
        dest.width( myWidth );
        return dest;
    }
};

(在我自己的代码中,我从保存格式的基类派生这些状态,并在完整表达式结束时将其恢复。)

这是相当普通的。在实践中,你会创建几个,带有名称如coordangle,以指定逻辑输出的内容。然而,你明白了。有了这个,你就可以写这样的东西:

std::cout << FFmt( 6, 2 ) << x << 't' << FFmt( 6, 2 ) << y << std::endl;