3-IOFormatting 367KB Jan 14 2015 07:25

Download Report

Transcript 3-IOFormatting 367KB Jan 14 2015 07:25

Output Formatting
No, I don't want 6 digits…
Standard Behavior
• Rules for printing decimals:
– No decimal point:
1.0000 prints as 1
– No trailing zeros:
1.5000 prints as 1.5
– Use 6 digits :
123.43289 prints as 123.433
– Scientific notation for large/small numbers:
1234567890.0 prints as 1.23457e+09
Output and Formatting Output
• cout accepts expressions or manipulators
– if expression , value is printed
– if manipulator, output format is modified
cout options
• Manipulators : special values that tell cout
how to do its job
cout << "Hey – show 2 decimal places" << 5.1234;
• Basic manipulator : endl
• Others in iomanip library
#include <iomanip>
showpoint Manipulator
• showpoint forces output to show the
decimal point and trailing zeros
• Example:
cout << 15.0 << " " << showpoint << 15.0 << " ";
cout << 4.0 << endl;
15 15.0000 4.0000
Persistent
fixed Manipulator
• fixed forces output as fixed decimal points:
cout << 1231234234.23123123 << endl;
1.23123e+009
cout << fixed;
cout << 1231234234.23123123 << endl;
1231234234.23123123
Persistent
fixed Manipulator
• Scientific:
output decimals as floating points
cout << fixed;
cout << 1231234234.23123123 << endl;
1231234234.23123123
cout << scientific;
cout << 1231234234.23123123 << endl;
1.23123e+009
Persistent
setprecision Manipulator
• setprecision(n)
– Number of decimal places before value is rounded
cout << fixed << setprecision(2);
cout << 15.128234 << " ";
cout << 435.3 << endl;
15.13 435.30
Persistent
setw
• setw(x)
– Makes next expression take up at least x columns
• Adds spaces to left
cout << 5 << setw(5) << 12 << endl;
5
12
......
– Longer expressions not affected:
cout << 5 << setw(2) << 12123;
512123
......
setw
• setw(x)
– Applies only to next expression
cout << setw(6) << 12 << 12;
1212
........
cout << setw(6) << 12
<< setw(6) << 12;
12
12
............
NOT Persistent
Additional Output Formatting Tools
• setfill(char)
– What char to use instead of spaces to fill columns
• left and right manipulators
– Which side to justify text
cout << left << setfill('*');
cout << setw(5) << 12 << 10;
12***10
Persistent
Goal
• Read in 2 numbers – numerator, denominator
• Print something like this:
Enter numbers: 2 3
Numerator/Denominator
2/3
Decimal Value
0.67
Goal
• Visualize spaces:
Enter numbers: 2 3
Numerator/Denominator..Decimal Value
........2/3............0.67
• Break into pieces:
........2
: right, width of 9
/
3.......... : left, width of 11
..
0.67
: 2 decimal places, fixed
Finished Program