Formatting output in C++

前端 未结 6 1173
既然无缘
既然无缘 2020-12-01 09:52

In a C++ code I have a matrix of double variables which I print out. However because all of them have different number of digits, the output format is destroyed. One solutio

6条回答
  •  渐次进展
    2020-12-01 09:56

    The key is, as others have said, to use manipulators. What they neglected to say is that you normally use manipulators that you write yourself. An FFmt manipulator (which corresponds to the F format in Fortran is fairly easy:

    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_base::fixed, std::ios_base::formatfield );
            dest.precision( myPrecision );
            dest.width( myWidth );
            return dest;
        }
    };
    

    This way, you can define a variable for each column, say:

    FFmt col1( 8, 2 );
    FFmt col2( 6, 3 );
    //  ...
    

    and write:

    std::cout  << col1 << value1
        << ' ' << col2 << value2...
    

    In general, except in the simplest programs, you should probably not be using the standard manipulators, but rather custom manipulators based on your application; e.g. temperature and pressure if that's the sort of thing your dealing with. In this way, it's clear in the code what you're formatting, and if the client suddenly asks for one more digit in the pressure, you know exactly where to make the change.

提交回复
热议问题