C++ 如何将填充零添加到写入流的数字中?

C++ 如何将填充零添加到写入流的数字中?,c++,padding,ofstream,C++,Padding,Ofstream,我试图将数值写入与列对齐的文本文件中。我的代码如下所示: ofstream file; file.open("try.txt", ios::app); file << num << "\t" << max << "\t" << mean << "\t << a << "\n"; 您需要先更改精度 有一个很好的例子。请看一看,并且。该方法与使用cout时的方法相同。请参阅。这取决于您想要的格式。对于固

我试图将数值写入与列对齐的文本文件中。我的代码如下所示:

ofstream file;
file.open("try.txt", ios::app);
file << num << "\t" << max << "\t" << mean << "\t << a << "\n";

您需要先更改精度


有一个很好的例子。

请看一看,并且。

该方法与使用
cout
时的方法相同。请参阅。

这取决于您想要的格式。对于固定小数点, 比如:

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& fmt )
    {
        dest.setf( std::ios::fixed, std::ios::floatfield );
        dest.precision( myPrecision );
        dest.width( myWidth );
    }
};
类FFmt
{
int-myWidth;
int-myPrecision;
公众:
FFmt(整数宽度、整数精度)
:myWidth(宽度)
,myPrecision(精度)
{
}

friend std::ostream&Operator答案的可能副本是您的答案。首先,您需要指定输出为固定格式,然后指定精度,并指定每个输出的宽度。谢谢,andrea,但我建议接受。这是更详细的方式。
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& fmt )
    {
        dest.setf( std::ios::fixed, std::ios::floatfield );
        dest.precision( myPrecision );
        dest.width( myWidth );
    }
};
file << nume << '\t' << FFmt( 8, 2 ) << max ...