Vous êtes sur la page 1sur 12

9

C Formatted Input/Output
All the news thats t to print.
Adolph S. Ochs

OBJECTIVES
In this chapter, you will learn:

What mad pursuit? What struggle to escape?


John Keats

To use input and output streams. To use all print formatting capabilities. To use all input formatting capabilities. To print with eld widths and precisions. To use formatting ags in the printf format control string. To output literals and escape sequences. To format input using scanf.

Remove not the landmark on the boundary of the elds.


Amenemope

Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 9 C Formatted Input/Output

Self-Review Exercises
9.1 Fill in the blanks in each of the following: a) All input and output is dealt with in the form of . ANS: streams. b) The stream is normally connected to the keyboard. ANS: standard input. c) The stream is normally connected to the computer screen. ANS: standard output. function. d) Precise output formatting is accomplished with the ANS: printf. e) The format control string may contain , , , and . ANS: Conversion specifiers, flags, field widths, precisions, literal characters. f) The conversion specifier or may be used to output a signed decimal integer. ANS: d, i. g) The conversion specifiers , and are used to display unsigned integers in octal, decimal and hexadecimal form, respectively. ANS: o, u, x (or X). h) The modifiers and are placed before the integer conversion specifiers to indicate that short or long integer values are to be displayed. ANS: h, l. i) The conversion specifier is used to display a floating-point value in exponential notation. ANS: e (or E). j) The modifier is placed before any floating-point conversion specifier to indicate that a long double value is to be displayed. ANS: L. k) The conversion specifiers e, E and f are displayed with digits of precision to the right of the decimal point if no precision is specified. ANS: 6. l) The conversion specifiers and are used to print strings and characters, respectively. ANS: s, c. m) All strings end in the character. ANS: NULL ('\0'). n) The field width and precision in a printf conversion specifier can be controlled with integer expressions by substituting a(n) for the field width or for the precision and placing an integer expression in the corresponding argument of the argument list. ANS: asterisk (*). o) The flag causes output to be left justified in a field. ANS: - (minus). p) The flag causes values to be displayed with either a plus sign or a minus sign. ANS: p) + (plus). q) Precise input formatting is accomplished with the function. ANS: scanf.

Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Self-Review Exercises

r) A(n) is used to scan a string for specific characters and store the characters in an array. ANS: scan set. s) The conversion specifier can be used to input optionally signed octal, decimal and hexadecimal integers. ANS: i. t) The conversion specifiers can be used to input a double value. ANS: le, lE, lf, lg or lG. is used to read data from the input stream and discard it without asu) The signing it to a variable. ANS: assignment suppression character (*). v) A(n) can be used in a scanf conversion specifier to indicate that a specific number of characters or digits should be read from the input stream. ANS: field width. 9.2 Find the error in each of the following and explain how the error can be corrected. a) The following statement should print the character 'c'. Correction: To print the character 'c', use the conversion specifier %c or change 'c' to "c". b) The following statement should print 9.375%. Correction: Use %% to print a literal % character. c) The following statement should print the first character of the string "Monday".
ANS: Error: Conversion specifier c expects an argument of type char.
printf( "%c\n", "Monday" );

ANS: Error: Conversion specifier s expects an argument of type pointer to char.

printf( "%s\n", 'c' );

ANS: Error: Trying to print the literal character % without using the conversion specifier %%.

printf( "%.3f%", 9.375 );

d) e) f)

Correction: To print the first character of "Monday" use the conversion specifier %1s.

ANS: Error: Trying to print the literal character " without using the \" escape sequence.

printf( ""A string in quotes"" );

Correction: Replace each quote in the inner set of quotes with \". Correction: Enclose %d%d in double quotes.

ANS: Error: The format control string is not enclosed in double quotes.
printf( "%c", "x" );

printf( %d%d, 12, 20 );

ANS: Error: The character x is enclosed in double quotes.

g)

Correction: Character constants to be printed with %c must be enclosed in single quotes. Correction: Use double quotes instead of single quotes to represent a string.

ANS: Error: The string to be printed is enclosed in single quotes.

printf( "%s\n", 'Richard' );

9.3

Write a statement for each of the following: a) Print 1234 right justified in a 10-digit field. b) Print 123.456789 in exponential notation with a sign (+ or -) and 3 digits of precision. c) Read a double value into variable number. d) Print 100 in octal form preceded by 0.
ANS: printf( "%#o\n", 100 ); ANS: scanf( "%lf", &number ); ANS: printf( "%+.3e\n", 123.456789 ); ANS: printf( "%10d\n", 1234 );

Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 9 C Formatted Input/Output


e) Read a string into character array string.
ANS: scanf( "%s", string );

f) Read characters into array n until a nondigit character is encountered. g) Use integer variables x and y to specify the field width and precision used to display the double value 87.4573.
ANS: printf( "%*.*f\n", x, y, 87.4573 ); ANS: scanf( "%[0123456789]", n );

h) Read a value of the form 3.5%. Store the percentage in float variable percent and eliminate the % from the input stream. Do not use the assignment suppression character. i) Print 3.333333 as a long double value with a sign (+ or -)in a field of 20 characters with a precision of 3.
ANS: printf( "%+20.3Lf\n", 3.333333 ); ANS: scanf( "%f%%", &percent );

Exercises
9.4 Show what is printed by each of the following statements. If a statement is incorrect, indicate why.
b) printf( "%c\n", "This is a string" ); ANS: A string cannot be printed with the %c specier. c) printf( "%*.*lf\n", 8, 3, 1024.987654 ); ANS: 1024.988 d) printf( "%#o\n%#X\n%#e\n", 17, 17, 1008.83689 ); 021 0X11 1.008837e+03 e) printf( "% ld\n%+ld\n", 1000000L, 1000000L ); a) printf( "%-10d\n", 10000 );

ANS: 10000

ANS:

ANS:

1000000 +1000000 f) printf( "%10.2E\n", 444.93738 ); ANS: 4.45E+02 preceded by two spaces g) printf( "%10.2g\n", 444.93738 ); ANS: 4.4e+02 preceded by three spaces h) printf( "%d\n", 10.987 );

ANS: A floating point value cannot be printed with the %d conversion specifier.

9.5 Write a program that loads 10-element array number with random integers from 1 to 1000. For each value, print the value and a running total of the number of characters printed. Use the %n conversion specifier to determine the number of characters output for each value. Print the total number of characters output for all values up to and including the current value each time the current value is printed. The output should have the following 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
ANS:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

/* Exercise 9.5 Solution */ #include <stdio.h> #include <stdlib.h> #include <time.h> int main( void ) { int a[ 10 ] = { 0 }; int i; int count; int totalCount = 0;

/* /* /* /*

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 */ /* print table headers */ printf( "%s\t%s\n", "Value", "Total characters" ); /* 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 */ return 0; /* indicate successful termination */ } /* end main */
Total characters 3 5 8 11 14 17 20 23 26 29

Value 842 18 220 658 275 647 657 623 242 471

9.6 Write a program that prints pointer values using all the integer conversion specifiers and the %p conversion specifier. Which ones print strange values? Which ones cause errors? In which format does the %p conversion specifier display the address on your system?

Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 9 C Formatted Input/Output


ANS:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

/* Exercise 9.6 Solution */ #include <stdio.h> int main( void ) { int x; /* define x for testing */ 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 Write a program to test the results of printing the integer value 12345 and the floating-point value 1.2345 in various size fields. What happens when the values are printed in fields containing fewer digits than the values?
ANS:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

/* Exercise 9.7 Solution */ #include <stdio.h> int main( void ) { /* 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

12345 12345 12345 1.234500 1.234500 1.234500

9.8 Write a program that prints the value 100.453627 rounded to the nearest digit, tenth, hundredth, thousandth and ten-thousandth.
ANS:

1 2 3 4 5 6 7 8 9 10 11 12 13 14

/* Exercise 9.8 Solution */ #include <stdio.h> int main( void ) { printf( "%.0f\n", printf( "%.1f\n", printf( "%.2f\n", printf( "%.3f\n", printf( "%.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

9.9 Write a program that inputs a string from the keyboard and determines the length of the string. Print the string using twice the length as the field width.
ANS:

1 2 3 4 5 6 7 8 9 10 11 12 13 14

/* Exercise 9.9 Solution */ #include <stdio.h> 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.

8
15 16 17

Chapter 9 C Formatted Input/Output


return 0; /* indicate successful termination */ } /* end main */

Enter a string: hello hello

9.10 Write a program that converts integer Fahrenheit temperatures from 0 to floating-point Celsius temperatures with 3 digits of precision. Use the formula
celsius = 5.0 / 9.0 * ( fahrenheit - 32 );

212

degrees to

to perform the calculation. The output should be printed in two right-justied columns of 10 characters each, and the Celsius temperatures should be preceded by a sign for both positive and negative values.
ANS:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

/* Exercise 9.10 Solution */ #include <stdio.h> 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 */
Celsius -17.778 -17.222 -16.667 -16.111 -15.556 -15.000 -14.444 -13.889

Fahrenheit 0 1 2 3 4 5 6 7 . . . 204 205 206 207 208 209 210 211 212

+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.11 Write a program that determines whether ? can be printed as part of a printf format control string as a literal character rather than using the \? escape sequence.
ANS:

1 2 3 4 5 6 7 8 9 10

/* Exercise 9.11 Solution */ #include <stdio.h> int main( void ) { printf( "Did the \? print at the end of the sentence?\n" ); return 0; /* indicate successful termination */ } /* end main */

Did the ? print at the end of the sentence?

9.12 Write a program that inputs the value 437 using each of the scanf integer conversion specifiers. Print each input value using all the integer conversion specifiers.
ANS:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

/* Exercise 9.12 Solution */ #include <stdio.h> int main( void ) { int array[ 5 ]; /* holds the value 437 five times */ int loop; /* loop counter */ /* 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++ ) { /* 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 */ return 0; /* indicate successful termination */ } /* end main */

Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

10

Chapter 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

this same value.


ANS:

1.2345. Print the values of each variable to prove that each conversion specifier can be used to input

9.13

Write a program that uses each of the conversion specifiers e,

and

to input the value

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

/* Exercise 9.13 Solution */ #include <stdio.h> int main( void ) { float a[ 3 ]; /* holds the value 1.2345 three times */ /* 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 */ } /* 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 entered surrounded by either single or double quotation marks. Write a program that reads the three strings suzy, "suzy" and 'suzy'. Are the single and double quotes ignored by C or read as part of the string?
ANS:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

/* Exercise 9.14 Solution */ #include <stdio.h> int main( void ) { char a[ 10 ]; /* first string */ char b[ 10 ]; /* second string */ char c[ 10 ]; /* third string */ /* 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'

9.15 Write a program that uses the conversion specifier g to output the value 9876.12345. Print the value with precisions ranging from 1 to 9.
ANS:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

/* Exercise 9.15 Solution */ #include <stdio.h> int main( void ) { /* 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 */
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 9876 9876.1 9876.12 9876.123 9876.1234 9876.12345

Precision: Precision: Precision: Precision: Precision: Precision: Precision: Precision: Precision:

Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Vous aimerez peut-être aussi