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

How can I add padding zeros to a number written to an ofstream?

本文关键字:数字 填充 添加      更新时间:2023-10-16

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

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

它是有效的,除非值的位数不相同,否则它们不会对齐。我想要的是以下内容:

1.234567  ->  1.234
1.234     ->  1.234
1.2       ->  1.200

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

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 ...

(或您想要的任何宽度和精度)。

如果你正在做任何浮点运算,你可能应该在你的Take工具包中有这样一个操纵器(尽管在许多情况下,它会更适合使用逻辑操纵器,以逻辑它格式化的数据的含义,例如度数、距离等)

IMHO,扩展操纵器也是值得的,这样它们就可以节省格式化状态,并在完整表达式结束时将其还原。(我所有的操纵器都派生自一个处理这个问题的基类。)

查看std::fixedstd::setw()std::setprecision()

您需要首先更改精度。

这里有一个很好的例子。

该方法与使用cout时相同。看看这个答案。