05 Formatted Input Output
05 Formatted Input Output
-1
-12
-123
-1234
-12345
Precisions for Integers, Floating-Point
Numbers and Strings
• printf enables you to specify the precision with which data is printed
• Different meanings for different types:
• For integer conversion specifiers, indicates minimum number of
digits to print
• For fewer digits than the specified precision, if the precision
value has a leading zero or decimal point, zeros are prefixed to
the printed value until the total number of digits is equivalent
to the precision. If neither a zero nor a decimal point is present
in the precision value, spaces are inserted instead. The default
precision for integers is 1.
Precisions for Integers, Floating-Point
Numbers and Strings
• For e, E and f, indicates the number of digits to appear after the
decimal point
• For g and G, indicates the maximum number of significant digits to
print
• For s, indicates the maximum number of characters written from
the beginning of the string
• To use precision, place a decimal point (.), followed by an integer
representing the precision between the percent sign and the
conversion specifier
Precisions for Integers, Floating-Point
Numbers and Strings
1. // Printing integers, floating-point numbers and strings
with precisions
2. #include <stdio.h>
3.
4. int main(void) {
5. puts("Using precision for integers");
6. int i = 873; // initialize int i
7. printf("\t%.4d\n\t%.9d\n\n", i, i);
8.
9. puts("Using precision for floating-point numbers");
10. double f = 123.94536; // initialize double f
11. printf("\t%.3f\n\t%.3e\n\t%.3g\n\n", f, f, f);
12.
13. puts("Using precision for strings");
14. char s[] = "Happy Birthday"; // initialize char array s
15. printf("\t%.11s\n", s);
16.}
Precisions for Integers, Floating-Point
Numbers and Strings
Output:
Using precision for integers
0873
000000873
Using precision for floating-point numbers
123.945
1.239e+02
124
Using precision for strings
Happy Birth
Printing Literals and Escape Sequences
• Literal characters included in the format control string are simply
output by printf
• There are several “problem” characters, such as the quotation mark
(") that delimits the format control string itself
• Various control characters, such as newline and tab, must be
represented by escape sequences
• An escape sequence is represented by a backslash (\), followed by a
particular escape character
Escape sequence Description
\' (single quote) Output the single quote (') character.
\" (double quote) Output the double quote (") character.
\? (question mark) Output the question mark (?) character.
\\ (backslash) Output the backslash (\) character.
\a (alert or bell) Cause an audible (bell) or visual alert (typically, flashing the window in
which the program is running).
\b (backspace) Move the cursor back one position on the current line.
\f (new page or form feed) Move the cursor to the next logical page’s start.