andrea
andrea

Reputation: 1358

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

I'm trying to write numeric values into a text file aligned to columns. My code looks like this:

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

It works, except if the values don't have the same number of digits, they don't align. What I would like is the following:

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

Upvotes: 3

Views: 5068

Answers (4)

NPE
NPE

Reputation: 500157

Take a look at std::fixed, std::setw() and std::setprecision().

Upvotes: 4

James Kanze
James Kanze

Reputation: 153889

It depends on what format you want. For a fixed decimal place, something like:

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 );
    }
};

should do the trick, so you can write:

file << nume << '\t' << FFmt( 8, 2 ) << max ...

(or whatever width and precision you want).

If you're doing any floating point work at all, you should probably have such a manipulator in your took kit (although in many cases, it will be more appropriate to use a logical manipulator, named after the logical meaning of the data it formats, e.g. degree, distances, etc.).

IMHO, it's also worth extending the manipulators so that they save the formatting state, and restore it at the end of the full expression. (All of my manipulators derive from a base class which handles this.)

Upvotes: 6

Samuel Harmer
Samuel Harmer

Reputation: 4412

The method is the same as when using cout. See this answer.

Upvotes: 2

Linus Kleen
Linus Kleen

Reputation: 34612

You'll need to alter the precision first.

There's a good example here.

Upvotes: 2

Related Questions