Formatting Data on Output

advertisement
Formatting Data on Output
When using C++, numeric values are not automatically formatted on output. There are a
few extra tasks you have to do as a programmer to format the data.
 Include the header iomanip.h in your program
 Use the setw object to define the number of spaces needed on output
 Use the setiosflags string manipulator
 Use setprecision specify the number of digits desired following the decimal
Following are statements which calculate an average and displays the data on the screen:
average = total/count;
cout << "\n The average temperature for this day is " << average;
The above output is not formatted. In order to format the data do the following:
// Add this header in your program
#include <iomanip.h>
// This statement remains the same
average = total/count;
// Change the cout statement to be as follows:
cout << "\n\nThe average temperature for this day is " << setw(4)
<< setiosflags(ios::fixed) << setprecision(2) << average;
When the value of average is displayed, it will have two digits to the right of the decimal
Download