3

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
Samuel Harmer
  • 4,264
  • 5
  • 33
  • 67
andrea
  • 1,326
  • 7
  • 31
  • 60
  • possible duplicate of [C++ stream output with 3 digits after the decimal point. How?](http://stackoverflow.com/questions/8554441/c-stream-output-with-3-digits-after-the-decimal-point-how) – Paul R Jan 24 '12 at 11:09

4 Answers4

6

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

James Kanze
  • 150,581
  • 18
  • 184
  • 329
4

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

NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

You'll need to alter the precision first.

There's a good example here.

Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
2

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

Community
  • 1
  • 1
Samuel Harmer
  • 4,264
  • 5
  • 33
  • 67