9 C Formatted Input/Output All t he he ne ws ws t ha t t’ s s fi t t o
pr in int . — A dolph dolph S. Ochs
OBJECTIVES
W ha t t ma d p ursui t t? ? W ha t t c a pe? stru ggle t o e s sca
In this chapter, you will learn:
ts — John K ea ts
■
To use input and o utput streams.
■
To use all p rint formatting capabilities.
R emo andm dma r emov e no t t he he l a n rk k r y of t t he ary on t he he b ound a he field s s.
■
To use all input formatting capabilities.
— A menemope menemope
■
To p rint with field widths and p recisions.
■
To use fo rmatting flags in the printf format control string.
■
To o utput literals and e scape sequences.
■
To fo rmat input using scanf.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter
2
9
C Formatted Input/Output
Self-R e v ie w Exercises 9.1
Fill in the blank s in e ach of the follo w ing: . a) A ll input and o utput is dealt w ith in the form of ANS: streams. stream i s normally connected to the key board. b) The ANS: standard input. stream i s normally connected to the computer screen. c) The ANS: standard o utput. d) Precise o utput formatting is accomplished w ith the f unction. ANS:
printf.
e) The format control string may contain , , , . and ANS: Conv ersion specifiers, flags, field w idths, precisions, literal characters. f) The conv ersion specifier or may be used to output a signed decimal in teger. ANS: d, i. g) The conv ersion specifiers , and are used to display u nsigned integers in o ctal, decimal and hexadecimal fo rm, respectiv ely . ANS: o, u, x (or X). h) The modifiers and are placed before the integer conv ersion specifiers t o indicate that short or long integer v alues are to be di splay ed. ANS: h, l. i) The conv ersion specifier is us ed to di splay a floating-point v alue in exponential no tation. ANS: e (or E). j) The modifier is placed before any floating-point conv ersion specifier to indicate that a long double v alue i s t o be di splay ed. ANS: L. k) The conv ersion specifiers e, E and f are di splay ed w ith digits of p recision to the right of the decimal point if no p recision is s pecified. ANS: 6. l) The conv ersion specifiers and are used to print strings and characters, respectiv ely . ANS: s, c. m) A ll strings end in the character. ANS: NULL ('\0'). n) The field w idth and precision in a printf conv ersion specifier can be controlled w ith integer expressions by substituting a(n) for the field w idth or for the p recision and placing an integer expression in the corresponding argument of the argument list. ANS: asterisk ( *). o) The flag causes output t o be lef t justified in a field. ANS: - (minus). p) The flag causes v alues to be display ed w ith either a plus sign or a minus sign. ANS: p) + (plus). q) Precise input formatting is accomplished w ith the f unction. ANS: scanf.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Self-R evie w Exercises
r) A (n)
3
is us ed to scan a string for s pecific characters and store the characters
in an array . ANS: scan set. s) The conv ersion specifier can be used to input optionally s igned octal, decimal and hexadecimal in tegers. ANS: i. t) The conv ersion specifiers can be used to input a double v alue. ANS: le, lE, lf, lg or lG. is used to read data f rom the input stream and discard it w ithout asu) The signing it t o a v ariable. ANS: assignment su ppression character (*). v ) A (n) can be used in a scanf conv ersion specifier t o indicate that a specific number of characters or digits s hould be read f rom the input stream. ANS: field w idth. 9.2
Find the e rror in e ach of the follo w ing and e xplain ho w t he e rror can be corrected. a) The follo w ing statement should p rint t he character 'c'. printf( "%s\n", 'c' ); ANS:
Error: Conv ersion specifier s expects an argument of ty pe pointer t o char. Correction: T o p rint t he character 'c', use the conv ersion specifier %c or change 'c'
to "c". b) The follo w ing statement should p rint 9.375%. printf( "%.3f%", 9.375 );
Error: Try ing to print the literal character % w ithout using the conv ersion specifier %%. Correction: Use %% to p rint a literal % character. c) The follo w ing statement should p rint t he first character of the string "Monday".
ANS:
printf( "%c\n", "Monday" ); ANS:
d)
printf( ""A string in q uotes"" );
ANS:
e)
Error: Try ing to p rint t he literal character " w ithout using the \" escape sequence. Correction: R eplace e ach q uote in the inner set of q uotes w ith \".
printf( %d%d, 12, 20 );
ANS:
f)
Error: Conv ersion specifier c expects an argument of ty pe char. Correction: To p rint t he first character of "Monday" use the conv ersion specifier %1s.
Error: The format control string is not enclosed in double q uotes. Correction: Enclose %d%d in double q uotes.
printf( "%c", "x" );
ANS:
Error: The character x is enclosed in double q uotes. Correction: Character constants t o be p rinted w ith %c must be en closed in single
quotes. g)
printf( "%s\n", 'Richard' );
ANS:
9.3
Error: The string to be p rinted i s enclosed in single quotes. Correction: Use do uble q uotes instead of single quotes t o represent a string.
W rite a statement for each of the follo w ing: a) Print 1234 right justified in a 10-digit field. ANS:
printf( "%10d\n", 1234 );
b) Print 123.456789 in e xponential no tation w ith a sign (+ or -) and 3 digits of p recision. ANS:
printf( "%+.3e\n", 123.456789 );
c) R ead a double v alue in to v ariable number. ANS:
scanf( "%lf", &number );
d) Print 100 in o ctal fo rm p receded by 0. ANS:
printf( "%#o\n", 100 );
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter
4
9
C Formatted Input/Output
e) R ead a string into character array string. ANS:
scanf( "%s", string );
f) R ead characters into array n until a nondigit character is encountered. ANS:
scanf( "%[0123456789]", n );
g) Use in teger v ariables x and y to specif y t he field w idth and precision used to display t he double v alue 87.4573. ANS:
printf( "%*.*f\n", x, y, 87.4573 );
h) R ead a v alue of the form 3.5%. Store the percentage in float v ariable percent and eliminate the % f rom the input stream. Do no t use the assignment suppression character. ANS:
scanf( "%f%%", &percent );
i) Print 3.333333 as a long double v alue w ith a sign (+ or -)in a field of 20 characters w ith a precision of 3. ANS:
printf( "%+20.3Lf\n", 3.333333 );
Exercises Sho w w hat is printed by each of the follo w ing statements. If a statement is incorrect, indi9.4 cate w hy . a) printf( "%-10d\n", 10000 ); ANS: 10000 b) printf( "%c\n", "This is a string" ); ANS: A string cannot be p rinted w ith the %c specifier. c) printf( "%*.*lf\n", 8, 3, 1024.987654 ); ANS: 1024.988 d) printf( "%#o\n%#X\n%#e\n", 17, 17, 1008.83689 ); ANS:
021 0X11
1.008837e+03 e) printf( "% ld\n%+ld\n", 1000000L, 1000000L ); ANS:
1000000 +1000000 f) printf( "%10.2E\n", 444.93738 ); pr e ce ded b y tw o s pac es ANS: 4.45E+02 g) printf( "%10.2g\n", 444.93738 ); pr ec eded b y t hr ee s pac e s ANS: 4.4e+02 h) printf( "%d\n", 10.987 ); ANS:
A floating point v alue cannot be p rinted w ith the %d conv ersion specifier.
W rite a program that loads 10-element array number w ith random integers f rom 1 to 1000. 9.5 For each v alue, print t he v alue and a running total of the n umber of characters printed. Use the %n conv ersion specifier to determine the number of characters output for each v alue. Print the total number of characters output for all v alues u p to and including the current v alue e ach time the current v alue i s printed. The o utput s hould h av e the follo w ing format: Value 342 1000 963 6 etc.
Total characters 3 7 10
11
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
5
ANS:
1 2 3
4 5
/* Exercise 9.5 Solution */ #include #include #include
6
int main( void )
7
{
8 9 10 11 12 13 14 15 16 17 18 19
int int int int
a[ 10 ] = { 0 }; i; count; totalCount = 0;
20
/* print table headers */ printf( "%s\t%s\n", "Value", "Total characters" );
/* /* /* /*
random integers from 1 to 1000 */ loop counter */ number of characters in current value */ total characters in array */
srand( time( NULL ) ); /* fill the array with random numbers */ for ( i = 0; i <= 9; i++ ) { a[ i ] = 1 + rand() % 1000; } /* end for */
21 22
/* loop through 10 elements */ for ( i = 0; i <= 9; i++ ) { printf( "%d%n", a[ i ], &count ); totalCount+= count; /* update totalCount */ printf( "\t%d\n", totalCount ); } /* end for */
23 24 25 26 27 28 29
return 0; /* indicate successful termination */
30 31 32
} /* end main */
Value 842
Total characters 3
18 220 658 275 647 657 623 242 471
5 8 11 14 17 20 23 26 29
9.6 W rite a program that prints pointer v alues using all the integer conv ersion specifiers and the %p conv ersion specifier. W hich ones print strange v alues? W hich ones cause errors? In w hich format does t he %p conv ersion specifier display t he address on y our system?
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter
6
9
C Formatted Input/Output
ANS:
1 2
/* Exercise 9.6 Solution */ #include
3
4 5
int main( void ) {
int x; /* define x for testing */
6 7
8 9 10 11 12 13 14 15 16 17 18
printf( printf( printf( printf( printf( printf( printf(
"%o\n", &x ); "%lo\n", &x ); "%d\n", &x ); "%ld\n", &x ); "%x\n", &x ); "%lx\n", &x ); "%p\n", &x );
return 0; /* indicate successful termination */ } /* end main */
4577574 4577574 1245052 1245052 12ff7c 12ff7c 0012FF7C
9.7 W rite a program to test the results of printing the integer v alue 12345 and the floating-point v alue 1.2345 in v arious size fields. W hat happens w hen the v alues are printed in fields containing fe w er digits t han the v alues? ANS:
1 2
/* Exercise 9.7 Solution */ #include
3
4 5
int main( void ) {
6 7
8 9 10 11 12 13 14 15 16 17 18 19
/* print the integer 12345 */ printf( "%10d\n", 12345 ); printf( "%5d\n", 12345 ); printf( "%2d\n\n", 12345 ); /* print the floating-point value 1.2345 */ printf( "%10f\n", 1.2345 ); printf( "%6f\n", 1.2345 ); printf( "%2f\n", 1.2345 ); return 0; /* indicate successful termination */ } /* end main */
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
7
12345 12345 12345 1.234500 1.234500 1.234500
W rite a program that prints t he v alue 100.453627 rounded to the nearest digit, tenth, hundredth, thousandth and ten-thousandth. 9.8
ANS:
/* Exercise 9.8 Solution */ #include
1 2 3
int main( void )
4 5
{
printf( printf( printf( printf( printf(
6 7
8 9 10 11 12 13 14
"%.0f\n", "%.1f\n", "%.2f\n", "%.3f\n", "%.4f\n",
100.453627 100.453627 100.453627 100.453627 100.453627
); ); ); ); );
return 0; /* indicate successful termination */ } /* end main */
100 100.5 100.45 100.454 100.4536
W rite a program that inputs a string f rom the key board and determines the length of the string. Print t he string using tw ice the length as t he field w idth. 9.9
ANS:
1 2
/* Exercise 9.9 Solution */ #include
3
4 5 6 7
8 9 10 11 12 13 14
int main( void ) {
int count; /* length of string */ char string[ 20 ]; /* string entered by user */ /* read string from user and find length */ printf( "Enter a string:\n" ); scanf( "%s%n", string, &count );
printf( "%*s\n", 2 * count, string ); /* print the string */
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter
8
15 16 17
9
C Formatted Input/Output
return 0; /* indicate successful termination */ } /* end main */
Enter a string:
hello hello
9.10 W rite a program that conv erts integer Fahrenheit temperatures f rom 0 to 212 floating-point Celsius t emperatures w ith 3 digits of p recision. Use the formula
degrees to
celsius = 5.0 / 9.0 * ( fahrenheit - 32 );
to perform the calculation. The output should be printed in tw o right-justified columns of 10 characters each, and the Celsius temperatures should be preceded by a sign for both positiv e and negativ e v alues. ANS:
1 2
/* Exercise 9.10 Solution */ #include
3
4 5 6 7
8 9 10 11 12 13 14 15 16 17 18 19 20
int main( void ) {
int fahrenheit; /* holds fahrenheit temperature */ double celsius; /* holds celcius temperature */ printf( "%10s%12s\n", "Fahrenheit", "Celsius" ); /* convert fahrenheit to celsius and display temperatures showing the sign for celsius temperatures */ for ( fahrenheit = 0; fahrenheit <= 212; fahrenheit++ ) { celsius = 5.0 / 9.0 * ( fahrenheit - 32 ); printf( "%10d%+12.3f\n", fahrenheit, celsius ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */
Fahrenheit 0
1 2 3 4 5 6 7 . . . 204 205 206 207 208 209 210 211 212
Celsius -17.778 -17.222 -16.667 -16.111 -15.556 -15.000
-14.444 -13.889
+95.556 +96.111 +96.667 +97.222 +97.778 +98.333 +98.889 +99.444 +100.000
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
9
W rite a program that determines w hether ? can be p rinted as part of a printf format control string as a literal character r ather than using the \? escape sequence. 9.11
ANS:
1 2
/* Exercise 9.11 Solution */ #include
3
4 5
int main( void ) {
printf( "Did the \? print at the end of the sentence?\n" );
6 7
8 9 10
return 0; /* indicate successful termination */ } /* end main */
Did th e ? print at the end of the sentence?
W rite a program that inputs the v alue 437 using each of the scanf integer conv ersion specifiers. Print each input v alue using all the integer conv ersion specifiers. 9.12
ANS:
1 2
/* Exercise 9.12 Solution */ #include
3
4 5 6 7
8 9 10 11 12 13 14 15 16 17 18 19
int main( void ) {
int array[ 5 ]; /* holds the value 437 five times */ /* loop counter */ int loop; /* array of table headers */ char *s[] = { "Read with %d:", "Read with %i:", "Read with %o:", "Read with %u:", "Read with %x:"}; /* prompt the user and read 5 values */ printf( "Enter the value 437 five times: " ); scanf( "%d%i%o%u%x", &array[ 0 ], &array[ 1 ], &array[ 2 ], &array[ 3 ], &array[ 4 ] ); /* loop through all 5 values */ for ( loop = 0; loop <= 4; loop++ ) {
20 21 22 23 24
/* print each of the 5 values */ printf( "%s\n%d %i %o %u %x\n\n", s[ loop ], array[ loop ], array[ loop ], array[ loop ], array[ loop ], array[ loop ] ); } /* end for */
25 26
return 0; /* indicate successful termination */
27 28
} /* end main */
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter
10
9
C Formatted Input/Output
Enter the value 437 five times: 437 437 437 437 437 Read with %d: 437 437 665 437 1b5 Read with %i: 437 437 665 437 1b5 Read with %o: 287 287 437 287 11f Read with %u: 437 437 665 437 1b5 Read with %x: 1079 1079 2067 1079 437
W rite a program that uses each of the conv ersion specifiers e, f and g to input the v alue 1.2345. Print t he v alues of each v ariable to prov e that each conv ersion specifier can be used to input this s ame v alue. 9.13
ANS:
1 2
/* Exercise 9.13 Solution */ #include
3
4 5 6
int main( void ) {
float a[ 3 ]; /* holds the value 1.2345 three times */
7
8 9 10 11 12 13 14 15 16 17 18 19
/* array of table headers */ char *s[] = { "Read with %e:", "Read with %f:", "Read with %g:" }; /* prompt the user and read 3 values */ printf( "Enter the value 1.2345 three times: " ); scanf( "%e%f%g", &a[ 0 ], &a[ 1 ], &a[ 2 ] );
printf( "%s%e\n\n", s[ 0 ], a[ 0 ] ); printf( "%s%f\n\n", s[ 1 ], a[ 1 ] ); printf( "%s%g\n\n", s[ 2 ], a[ 2 ] ); return 0; /* indicate successful termination */
20 21
} /* end main */
Enter the value 1.2345 three times: 1.2345 1.2345 1.2345 Read with %e:1.234500e+000 Read with %f:1.234500 Read with %g:1.2345
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
11
9.14 In some programming languages, strings are en tered surrounded by either s ingle or double quotation mark s. W rite a program that r eads t he three strings suzy, "suzy" and 'suzy'. A re the single and double q uotes ignored by C or read as part of the string? ANS:
1 2
/* Exercise 9.14 Solution */ #include
3
4 5
int main( void ) { char a[ 10 ]; /* first string */ char b[ 10 ]; /* second string */ char c[ 10 ]; /* third string */
6 7
8 9 10 11 12 13 14 15 16 17 18
/* prompt user and read three strings */ printf( "Enter the strings suzy, \"suzy\", and 'suzy':\n" ); scanf( "%s%s%s", a , b , c );
printf( "%s %s %s\n", a , b , c ); /* display strings */ return 0; /* indicate successful termination */ } /* end main */
Enter the strings suzy, "suzy", and 'suzy': suzy "suzy" 'suzy' suzy "suzy" 'suzy'
W rite a program that uses t he conv ersion specifier g to o utput t he v alue 9876.12345. Print the v alue w ith p recisions r anging f rom 1 to 9. 9.15
ANS:
1 2
/* Exercise 9.15 Solution */ #include
3
4 5
int main( void ) {
6 7
8 9 10 11 12 13 14 15 16 17
/* output the value printf( "Precision: printf( "Precision: printf( "Precision: printf( "Precision: printf( "Precision: printf( "Precision: printf( "Precision: printf( "Precision: printf( "Precision:
9876.12345 with precisions from 1 to 9 */ %d, value = %.1g\n", 1, 9876.12345 ); %d, value = % .2g\n", 2, 9876.12345 ); %d, value = % .3g\n", 3, 9876.12345 ); %d, value = %.4g\n", 4, 9876.12345 ); %d, value = %.5g\n", 5, 9876.12345 ); %d, value = % .6g\n", 6, 9876.12345 ); %d, value = % .7g\n", 7, 9876.12345 ); %d, value = %.8g\n", 8, 9876.12345 ); %d, value = %.9g\n", 9, 9876.12345 );
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
12
18 19 20
Chapter
9
C Formatted Input/Output
return 0; /* indicate successful termination */ } /* end main */
Precision: Precision: Precision: Precision: Precision: Precision: Precision: Precision: Precision:
1, 2, 3, 4, 5, 6, 7, 8, 9,
value value value value value value value value value
= = = = = = = = =
1e+004 9.9e+003 9.88e+003 9 876 9 876.1 9 876.12 9 876.123 9 876.1234 9 876.12345
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.