News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

C++ TIPS:IO - Setting output width with iostreams

Started by ben2ong2, October 06, 2006, 11:11:31 PM

Previous topic - Next topic

0 Members and 2 Guests are viewing this topic.

ben2ong2

PROBLEM: You are not allowed to view links. Register or Login (Richard Levitte)

I personally like the C++ iostreams very much, and I find the
operator<<(ostream&, <whatever>) quite usable, except for one
thing. There is no way, as far as I know, to specify a field
size for some particular argument to output.

What I would like is something similar to printf("%6.4f", f)!
Is this possible? Is there some predefined manipulator I can
use, or do I have to do this myself?



RESPONSE: You are not allowed to view links. Register or Login (Steve Clamage), 1 Mar 93

Use the "width" and "precision" functions in the stream.  The
give effectively the same result as with printf formats.

   cout.width(6);
   cout.precision(4);
   cout << f;

More conveniently, two manipulators are provided in <iomanip.h>:

   cout << setw(6) << setprecision(4) << f;

You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login