Formatted output

B

bintom

Say, I have the following lines in my program:

cout << setw(8) << 23.56 << "\n";
cout << setw(8) << 7043.345 << "\n";
cout << setw(8) << 85;

The above program outputs

23.56
7043.35
85

I want the output to be formatted so that each number is displayed to
exactly 2 decimal places and is right aligned as shown below:

23.56
7043.35
85.00

How do I get this done?

Bintom
 
B

bintom

The above post doesn't match the look I had in mind, probably becos of
the way HTML formats text. Anyway, I want the output to be in neatly
ordered columnnar form, with the decimal point on each row aligned
exactly below each other and the value correct to 2 decimal places.

Thanks,
Bintom
 
J

James Kanze

You need to add 'setprecision' and 'fixed' to the used
manipulators. Generally speaking, it's possible to achieve
almost exactly the same result as with 'printf' by using
'setw', 'setprecision', 'fixed' vs 'scientific', 'fill', etc.
You need to RTFM on stream manipulators.

For starters. In actual practice, you'd probably define
a custom manipulator, with some semantically significant name,
and set the various options in that. Something like the
following:

class TableColFmt
{
int width;
int precision;
public:
TableColFmt( int width, int precision )
: width( width )
, precision( precision )
{
}
friend std::eek:stream& operator<<( std::eek:stream& dest,
TableColFmt const& fmt )
{
dest.setf( std::ios::fixed, std::ios::floatfield );
dest.precision( fmt.precision );
dest.width( fmt.width );
return dest;
}
};

TableColFmt
tablecol( int width, int precision )
{
return TableColFmt( width, precision );
}

// ...
std::cout << tablecol( 8, 2 ) << *iter << '\n';

This isn't perfect, because it results in a permanent change in
the formatting state of the stream; it's relatively simple,
however, for TableColFmt to restore the initial state in its
destructor, and since it will always be used as a temporary
object, that means at the end of the full expression.
 
B

bintom

Thanks to Victor and James, Victor especially, since his advice on
using ios::fixed with ios::showpoint and setprecision did the trick
for me. Here is how it is:

cout.precision(2);
cout.setf(ios::showpoint | ios::fixed);
cout << setw(10) << sal << "\n";

Very obliged for the kind help

Bintom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,044
Latest member
RonaldNen

Latest Threads

Top