Chtp5e Pie Sm 09

12
9 C Formatted Input/Output OBJECTIVES In this chapter, you will learn: To use input and output streams. To use all print formatting capabilities. To use all input formatting capabilities. To print with field widths and precisions. To use formatting flags in the printf format control string. To output literals and escape sequences. To format input using scanf. All the news that’s fit to print. —Adolph S. Ochs What mad pursuit? What struggle to escape? —John Keats Remove not the landmark on the boundary of the fields. —Amenemope

Transcript of Chtp5e Pie Sm 09

Page 1: Chtp5e Pie Sm 09

9C FormattedInput/Output

O B J E C T I V E SIn this chapter, you will learn:

■ To use input and output streams.

■ To use all print formatting capabilities.

■ To use all input formatting capabilities.

■ To print with field widths and precisions.

■ To use formatting flags in the printf format controlstring.

■ To output literals and escape sequences.

■ To format input using scanf.

All the news that’s fit toprint.—Adolph S. Ochs

What mad pursuit? Whatstruggle to escape?—John Keats

Remove not the landmarkon the boundary of the fields.—Amenemope

Page 2: Chtp5e Pie Sm 09

2 Chapter 9 C Formatted Input/Output

Self-Review Exercises9.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.d) Precise output formatting is accomplished with the function.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 dis-

play 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 expo-

nential notation.ANS: e (or E).j) The modifier is placed before any floating-point conversion specifier to in-

dicate 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 pre-cision and placing an integer expression in the corresponding argument of the argumentlist.

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.

Page 3: Chtp5e Pie Sm 09

Self-Review Exercises 3

r) A(n) is used to scan a string for specific characters and store the charactersin an array.

ANS: scan set.s) The conversion specifier can be used to input optionally signed octal, dec-

imal and hexadecimal integers.ANS: i.t) The conversion specifiers can be used to input a double value.ANS: le, lE, lf, lg or lG.u) The is used to read data from the input stream and discard it without as-

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'.

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

ANS: Error: Conversion specifier s expects an argument of type pointer to char.Correction: To print the character 'c', use the conversion specifier %c or change 'c'

to "c".b) The following statement should print 9.375%.

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

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

c) The following statement should print the first character of the string "Monday".printf( "%c\n", "Monday" );

ANS: Error: Conversion specifier c expects an argument of type char.Correction: To print the first character of "Monday" use the conversion specifier %1s.

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

ANS: Error: Trying to print the literal character " without using the \" escape sequence.Correction: Replace each quote in the inner set of quotes with \".

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

ANS: Error: The format control string is not enclosed in double quotes.Correction: Enclose %d%d in double quotes.

f) printf( "%c", "x" );

ANS: Error: The character x is enclosed in double quotes.Correction: Character constants to be printed with %c must be enclosed in singlequotes.

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

ANS: Error: The string to be printed is enclosed in single quotes.Correction: Use double quotes instead of single quotes to represent a string.

9.3 Write a statement for each of the following:a) Print 1234 right justified in a 10-digit field.ANS: printf( "%10d\n", 1234 );

b) Print 123.456789 in exponential notation with a sign (+ or -) and 3 digits of precision.ANS: printf( "%+.3e\n", 123.456789 );

c) Read a double value into variable number.ANS: scanf( "%lf", &number );

d) Print 100 in octal form preceded by 0.ANS: printf( "%#o\n", 100 );

Page 4: Chtp5e Pie Sm 09

4 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.ANS: scanf( "%[0123456789]", n );

g) Use integer variables x and y to specify the field width and precision used to display thedouble value 87.4573.

ANS: printf( "%*.*f\n", x, y, 87.4573 );

h) Read a value of the form 3.5%. Store the percentage in float variable percent and elim-inate the % from the input stream. Do not use the assignment suppression character.

ANS: scanf( "%f%%", &percent );

i) Print 3.333333 as a long double value with a sign (+ or -)in a field of 20 characters witha precision of 3.

ANS: printf( "%+20.3Lf\n", 3.333333 );

Exercises9.4 Show what is printed by each of the following statements. If a statement is incorrect, indi-cate why.

a) printf( "%-10d\n", 10000 );ANS: 10000b) printf( "%c\n", "This is a string" );ANS: A string cannot be printed with the %c specifier.c) printf( "%*.*lf\n", 8, 3, 1024.987654 );ANS: 1024.988d) printf( "%#o\n%#X\n%#e\n", 17, 17, 1008.83689 );ANS:

021

0X11

1.008837e+03e) printf( "% ld\n%+ld\n", 1000000L, 1000000L );ANS:

1000000

+1000000f) printf( "%10.2E\n", 444.93738 );ANS: 4.45E+02 preceded by two spacesg) printf( "%10.2g\n", 444.93738 );ANS: 4.4e+02 preceded by three spacesh) 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 %nconversion specifier to determine the number of characters output for each value. Print the totalnumber of characters output for all values up to and including the current value each time the cur-rent value is printed. The output should have the following format:

Value Total characters342 31000 7963 106 11etc.

Page 5: Chtp5e Pie Sm 09

Exercises 5

ANS:

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 formatdoes the %p conversion specifier display the address on your system?

1 /* Exercise 9.5 Solution */2 #include <stdio.h>3 #include <stdlib.h>4 #include <time.h>56 int main( void )7 {8 int a[ 10 ] = { 0 }; /* random integers from 1 to 1000 */9 int i; /* loop counter */

10 int count; /* number of characters in current value */11 int totalCount = 0; /* total characters in array */1213 srand( time( NULL ) );1415 /* fill the array with random numbers */16 for ( i = 0; i <= 9; i++ ) {17 a[ i ] = 1 + rand() % 1000;18 } /* end for */1920 /* print table headers */21 printf( "%s\t%s\n", "Value", "Total characters" );2223 /* loop through 10 elements */24 for ( i = 0; i <= 9; i++ ) {25 printf( "%d%n", a[ i ], &count );26 totalCount+= count; /* update totalCount */27 printf( "\t%d\n", totalCount );28 } /* end for */2930 return 0; /* indicate successful termination */3132 } /* end main */

Value Total characters842 318 5220 8658 11275 14647 17657 20623 23242 26471 29

Page 6: Chtp5e Pie Sm 09

6 Chapter 9 C Formatted Input/Output

ANS:

9.7 Write a program to test the results of printing the integer value 12345 and the floating-pointvalue 1.2345 in various size fields. What happens when the values are printed in fields containingfewer digits than the values?

ANS:

1 /* Exercise 9.6 Solution */2 #include <stdio.h>34 int main( void )5 {6 int x; /* define x for testing */78 printf( "%o\n", &x );9 printf( "%lo\n", &x );

10 printf( "%d\n", &x );11 printf( "%ld\n", &x );12 printf( "%x\n", &x );13 printf( "%lx\n", &x );14 printf( "%p\n", &x );1516 return 0; /* indicate successful termination */1718 } /* end main */

457757445775741245052124505212ff7c12ff7c0012FF7C

1 /* Exercise 9.7 Solution */2 #include <stdio.h>34 int main( void )5 {67 /* print the integer 12345 */8 printf( "%10d\n", 12345 );9 printf( "%5d\n", 12345 );

10 printf( "%2d\n\n", 12345 );1112 /* print the floating-point value 1.2345 */13 printf( "%10f\n", 1.2345 );14 printf( "%6f\n", 1.2345 );15 printf( "%2f\n", 1.2345 );1617 return 0; /* indicate successful termination */1819 } /* end main */

Page 7: Chtp5e Pie Sm 09

Exercises 7

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

ANS:

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

ANS:

123451234512345

1.2345001.2345001.234500

1 /* Exercise 9.8 Solution */2 #include <stdio.h>34 int main( void )5 {6 printf( "%.0f\n", 100.453627 );7 printf( "%.1f\n", 100.453627 );8 printf( "%.2f\n", 100.453627 );9 printf( "%.3f\n", 100.453627 );

10 printf( "%.4f\n", 100.453627 );1112 return 0; /* indicate successful termination */1314 } /* end main */

100100.5100.45100.454100.4536

1 /* Exercise 9.9 Solution */2 #include <stdio.h>34 int main( void )5 {6 int count; /* length of string */7 char string[ 20 ]; /* string entered by user */89 /* read string from user and find length */

10 printf( "Enter a string:\n" );11 scanf( "%s%n", string, &count );1213 printf( "%*s\n", 2 * count, string ); /* print the string */14

Page 8: Chtp5e Pie Sm 09

8 Chapter 9 C Formatted Input/Output

9.10 Write a program that converts integer Fahrenheit temperatures from 0 to 212 degrees tofloating-point Celsius temperatures with 3 digits of precision. Use the formula

celsius = 5.0 / 9.0 * ( fahrenheit - 32 );

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

ANS:

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

Enter a string:hello

hello

1 /* Exercise 9.10 Solution */2 #include <stdio.h>34 int main( void )5 {6 int fahrenheit; /* holds fahrenheit temperature */7 double celsius; /* holds celcius temperature */89 printf( "%10s%12s\n", "Fahrenheit", "Celsius" );

1011 /* convert fahrenheit to celsius and display temperatures12 showing the sign for celsius temperatures */13 for ( fahrenheit = 0; fahrenheit <= 212; fahrenheit++ ) {14 celsius = 5.0 / 9.0 * ( fahrenheit - 32 );15 printf( "%10d%+12.3f\n", fahrenheit, celsius );16 } /* end for */1718 return 0; /* indicate successful termination */1920 } /* end main */

Fahrenheit Celsius0 -17.7781 -17.2222 -16.6673 -16.1114 -15.5565 -15.0006 -14.4447 -13.889...

204 +95.556205 +96.111206 +96.667207 +97.222208 +97.778209 +98.333210 +98.889211 +99.444212 +100.000

Page 9: Chtp5e Pie Sm 09

Exercises 9

9.11 Write a program that determines whether ? can be printed as part of a printf format con-trol string as a literal character rather than using the \? escape sequence.

ANS:

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

ANS:

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

10 } /* end main */

Did the ? print at the end of the sentence?

1 /* Exercise 9.12 Solution */2 #include <stdio.h>34 int main( void )5 {6 int array[ 5 ]; /* holds the value 437 five times */7 int loop; /* loop counter */89 /* array of table headers */

10 char *s[] = { "Read with %d:", "Read with %i:", "Read with %o:",11 "Read with %u:", "Read with %x:"};1213 /* prompt the user and read 5 values */14 printf( "Enter the value 437 five times: " );15 scanf( "%d%i%o%u%x", &array[ 0 ], &array[ 1 ], &array[ 2 ],16 &array[ 3 ], &array[ 4 ] );1718 /* loop through all 5 values */19 for ( loop = 0; loop <= 4; loop++ ) {2021 /* print each of the 5 values */22 printf( "%s\n%d %i %o %u %x\n\n", s[ loop ], array[ loop ],23 array[ loop ], array[ loop ], array[ loop ], array[ loop ] );24 } /* end for */2526 return 0; /* indicate successful termination */2728 } /* end main */

Page 10: Chtp5e Pie Sm 09

10 Chapter 9 C Formatted Input/Output

9.13 Write a program that uses each of the conversion specifiers e, f and g to input the value1.2345. Print the values of each variable to prove that each conversion specifier can be used to inputthis same value.

ANS:

Enter the value 437 five times: 437 437 437 437 437Read 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

1 /* Exercise 9.13 Solution */2 #include <stdio.h>34 int main( void )5 {6 float a[ 3 ]; /* holds the value 1.2345 three times */78 /* array of table headers */9 char *s[] = { "Read with %e:", "Read with %f:", "Read with %g:" };

1011 /* prompt the user and read 3 values */12 printf( "Enter the value 1.2345 three times: " );13 scanf( "%e%f%g", &a[ 0 ], &a[ 1 ], &a[ 2 ] );1415 printf( "%s%e\n\n", s[ 0 ], a[ 0 ] );16 printf( "%s%f\n\n", s[ 1 ], a[ 1 ] );17 printf( "%s%g\n\n", s[ 2 ], a[ 2 ] );1819 return 0; /* indicate successful termination */2021 } /* end main */

Enter the value 1.2345 three times: 1.2345 1.2345 1.2345Read with %e:1.234500e+000

Read with %f:1.234500

Read with %g:1.2345

Page 11: Chtp5e Pie Sm 09

Exercises 11

9.14 In some programming languages, strings are entered surrounded by either single or doublequotation marks. Write a program that reads the three strings suzy, "suzy" and 'suzy'. Are the sin-gle and double quotes ignored by C or read as part of the string?

ANS:

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

ANS:

1 /* Exercise 9.14 Solution */2 #include <stdio.h>34 int main( void )5 {6 char a[ 10 ]; /* first string */7 char b[ 10 ]; /* second string */8 char c[ 10 ]; /* third string */9

10 /* prompt user and read three strings */11 printf( "Enter the strings suzy, \"suzy\", and 'suzy':\n" );12 scanf( "%s%s%s", a, b, c );1314 printf( "%s %s %s\n", a, b, c ); /* display strings */1516 return 0; /* indicate successful termination */1718 } /* end main */

Enter the strings suzy, "suzy", and 'suzy':suzy"suzy"'suzy'suzy "suzy" 'suzy'

1 /* Exercise 9.15 Solution */2 #include <stdio.h>34 int main( void )5 {67 /* output the value 9876.12345 with precisions from 1 to 9 */8 printf( "Precision: %d, value = %.1g\n", 1, 9876.12345 );9 printf( "Precision: %d, value = %.2g\n", 2, 9876.12345 );

10 printf( "Precision: %d, value = %.3g\n", 3, 9876.12345 );11 printf( "Precision: %d, value = %.4g\n", 4, 9876.12345 );12 printf( "Precision: %d, value = %.5g\n", 5, 9876.12345 );13 printf( "Precision: %d, value = %.6g\n", 6, 9876.12345 );14 printf( "Precision: %d, value = %.7g\n", 7, 9876.12345 );15 printf( "Precision: %d, value = %.8g\n", 8, 9876.12345 );16 printf( "Precision: %d, value = %.9g\n", 9, 9876.12345 );17

Page 12: Chtp5e Pie Sm 09

12 Chapter 9 C Formatted Input/Output

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

Precision: 1, value = 1e+004Precision: 2, value = 9.9e+003Precision: 3, value = 9.88e+003Precision: 4, value = 9876Precision: 5, value = 9876.1Precision: 6, value = 9876.12Precision: 7, value = 9876.123Precision: 8, value = 9876.1234Precision: 9, value = 9876.12345