%[-][0][col][.prec]typeThe - character is optional and will left justify the text (right justify is the default if - is omited).
d
for an integer, f
for a double (or float)
and c
for a character. There are other types available. See
man printf
for a list.
Examples:
printf("%d", num);
printf("%f", dnum);
printf("%.2f", dnum);
printf("%10d", num);
printf("%10.3f", dnum);
printf("%-10d", num);
printf("%010d", num);
#include <iostream> #include <stdio.h> using namespace std; int main() { int num1, num2; double dnum1, dnum2; printf("Enter two integers: "); cin >> num1 >> num2; printf("Enter two doubles: "); cin >> dnum1 >> dnum2; printf("%d %d %f %f.\n", num1, num2, dnum1, dnum2); printf("%10d %10d %10f %10f.\n", num1, num2, dnum1, dnum2); printf("%010d %-10d %10.2f %10.4f.\n", num1, num2, dnum1, dnum2); return 0; }
setw(<intExpr>)
- Set the width of the column. It has to
be within a cout statement. Example:
cout << setw(10) << num;
precision(<intExpr>)
- Set the precision for the output.
Should be combined with setting fixed and showpoint (see below) for best
looking output. Example: cout.precision(4);
setf(<flag>)
- Set a certain flag on the iostream. Common
flags are:
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.setf(ios::right);
unsetf
(see below).
Example: cout.setf(ios::left)
unsetf(<flag>)
- Clear a flag on the iostream. It uses
similar flags to setf
. Example:
cout.unsetf(ios::right);
cout << setprecision(2) << fixed << showpoint << dnum;
left
- Do left justification until right justification is set.
Example: cout << left << num;
right
- Turn off left justification and go back to right
justification. Example: cout << right << num;
integer output right justify: | 5| left justify: |5 | double output (2 precision) right justify: | 5.50| left justify: |5.50 | A small table without borders: Name Integer Double Alice 5 6.20 Bob 8 13.34 Carol 12 19.00Copy the file over to your current directory using the following command (note: there is a dot at the end of the command, this represents the current working directory is the destination of the copy command):
cp /home/fac/melissa/public_html/cs221-f09/lab5_example.cpp .Compile and run the code. You should see output similar to above.