Formatting

So far in the course we used simple unformatted output. We wrote a statement like:

cout << " This is my result \n " << sum;

which produced the string "This is my result " and the data stored in the location named sum. Of course the ability to change line using \ n is a formatting ability we had. Similarly if we wanted to leave space between two outputted numbers we can always send an empty string in between as in the example:

cout << a << " " << b;

However we would like to have better tools in producing good-looking output. Engineers prefer to communicate their numerical results and summaries in form of tables. You have heard the saying " a picture is worth a thousand words". Tables are almost as valuable as pictures ( graphs ) in presenting numerical data, but in addition they can be very precise. And we all know the fixation of engineers with precision ( a bridge cannot afford to nearly stand) . In order to produce this sort of orderly output we use the following functions, which are contained in the <iomanip.h> header:

setiosflags( ios:: fixed) suppose we send this function to a particular stream. After this, any data to the same stream, is sent as a floating point decimal number.
setiosflags( ios:: scientific) suppose we send this function to a particular stream. After this, any data to the same stream, is sent as a number in scientific notation.
setprecision ( k) suppose we send this function to a particular stream. Any data after it, it is sent as a number with k decimal digits after the point ( in either fixed or scientific form)
setw( k ) Each time we send this function to a stream, we open up k places for the data following the above function

For example if we have

float temperature = 123.4567;

cout << setiosflags(ios::scientific) << " temp = " << temperature;

We will get the output:

temp = 1.23457e+02

In addition, if we have:

float temperature = 123.4567;

cout << setiosflags(ios::scientific) << setprecision(3) << " temp = " << temperature;

We will get the output:

Temp = 1.235e+02

In Visual C++ , when we want to switch from fixed format to scientific or vice versa, we must send to the stream the command resetiosflags as shown in the example below:

cout << setiosflags( ios :: fixed ) << temperature ;

cout << resetiosflags( ios :: fixed ) ;

cout << setiosflags( ios :: scientific) << pressure ;

Jacob Y. Kazakia © 2001 All rights reserved