chapter 9 c formatted...

35
Chapter 9 C Formatted Input/Output

Upload: hoangminh

Post on 28-Apr-2018

225 views

Category:

Documents


5 download

TRANSCRIPT

Chapter 9

C Formatted Input/Output

Objectives of This Chapter

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.

Page 389An important part of the programming is to present the results in the desired format.

In this chapter, we will learn in depth the formatting features of scanf and printf functions used to input and output from the standard input stream (keyboard) and output data to the standard output stream (screen).

Many features of printf and scanf have been already presented in the previous lectures.

This chapter will summarizes those features and introduces some new ones.

Page 389The printf function has the form

printf( format-control-string, other-arguments );Format-control-string is used to the output format (eg. %s %d …)Other-arguments includes the values corresponding to each conversion specification (place holders) in format-control-string.

Precise output formatting can be accomplished using the formatting features in the format-control-string of printf function.

Printf output formatting presents the followings features:

Page 390Table below describes the conversion specifiers that can be used to print an integer number using printf function.

Remember:%c can be used to print corresponding character of an integer in ASCII table.

Using Integer Conversion Specifiers –Example- Page 390

Note:%d or %i doesn’t print + sign for positive numbers. It is possible to + sign in front of positive numbers.We will learn this capability in Section 9.9

* Output of the Program *

Page 391A floating-point number contains a decimal point as 33.5 or -45.78

The floating-point numbers can be displayed in different formats.

The conversion specifiers that can be used to display a floating point-number are listed in the table below.

Exponential Notation – Scientific Notation ( %E ): 3.49×10-9 = 3.49E-09%G prints in floating point form or exponential notationPrints in exponential notation if exponent < -4 or exponent >= 6 .Also it doesn’t put trailing zeros. 1.234000 is printed as 1.234 with %g

Using Floating-Point Conversion Specifiers –Example- Page 393

Note:Conversion specifiers doesn’t print + sign. %G prints in E or f format depending on the magnitude.%G prints 6 significant digits when printing in E notation. %f prints 6 digits after decimal point.%G or %g doesn’t put trailing zeros.

* Output of the Program *

Page 393The c and s conversion specifiers are used to print individual characters and strings, respectively.

Conversion specifier c requires a char argument.

Conversion specifier s requires a pointer to char as an argument.

Conversion specifier s causes characters to be printed until a terminating null ('\0') character is encountered.

Printing Strings and Characters –Example- Page 394

* Output of the Program *

Page 394Three other conversion specifiers are p, n, and %Conversion specifier p prints the memory address.

Conversion specifier n doesn’t print anything. It is used to determine number of characters printed up to %n in printffunction. An integer pointer should be supplied as argument. Conversion specifier % prints the % character.

Below table presents the description of these specifiers

Other Conversion Specifiers (p, n and %) –Example- Page 395

* Output of the Program *

Page 395The size of a field in which data is printed can be also defined in format-controlling string and called field width.

An integer representing the field width is inserted between the percent sign (%) and the conversion specifier (e.g., %4d or %5s).

If the field width is larger than the data being printed, the data will normally be right justified/right aligned within that field.

The field width is increased to print values wider than the field and that the minus sign for a negative value uses one character position in the field width.

Field widths can be used with all conversion specifiers.

Printing with Width Fields –Example- Page 395* Output of the Program *

Page 395In addition to field width, also precision of a variable can be defined in format-controlling string.

Precision is defined between % and specifier with an integer number after “.”. (e.g. %.5f , %.5d , and %.4s )

Precision has different meanings for the different data types.

Float Number Precision:In %E and %f : the number of digits after decimal point.In %G : the number significant digits to be printed.

Integer Precision: Minimum number of digits to be printed.

String Precision: Maximum Number of characters to be printed.

Printing with Field Widths and Precision –Example- Page 397

* Output of the Program *

Page 398Function printf also provides flags as supplement to its output formatting features.

Five flags are available for use in format control string. Flags are placed immediately after % (e.g. %-10.5d)

Several flags may be combined in one conversion specifier.

Using Left Justification Flag ( - ) –Example- Page 399

* Output of the Program *

Using + and space flags –Example- Page 399

* Output of the Program *

Using 0 (zero) flag and Combining Flags –Example- Page 400

* Output of the Program *

Page 401Most literal characters to be printed in a printf statement can simply be included in the format control string.

However, there are several “problem” characters (e.g. “ , \ , or ` ) .

Various control characters, such as newline and tab, must be represented by escape sequences ( \ followed by a character ).

Below table lists the escape sequences and the actions they cause.

Page 401Precise formatting can be also accomplished with scanf

scanf( format-control-string, other-arguments );Format-control-string is used to define the input format (eg. %s %d …)Other-arguments includes the pointers to variables to store inputted data.

scanf is capable of the following input capabilities1. Inputting all types of data.2. Inputting specific characters.3. Skipping specific characters from input stream.

Conversion Specifiers in formatted input with scanf Page 400List of the conversion specifiers used to input all types of data**.

Note:  %% is used to skip %‐or / (slash)  or any othercharacters can be skippedwithout using %

In printf %d and %i are the same.But in scanf, %d only can input decimal ints.

Inputting Integer and Double Values –Example- Page 403

* Output of the Program *

Inputting Character and String Values –Example- Page 404

* Output of the Program *

%c%s first reads a character then the rest as string.

Using scan set in scanf –Example- Page 405A sequence of desired characters can be inputted using scan set.A scan set is set of character included [ ] following % .

* Output of the Program *

%[aeiou] causes scanf to input only character listed in [].

Using inverted scan set in scanf–Example- Page 405An inverted scan set can be used to input the characters upto a desired set of characters. Usage is similar to scan set but (caret) ^ in from of [].

%[aeiou] causes scanf to input until a character entered listed in […].

* Output of the Program *

Using field widths in scanf –Example- Page 406A field width can be used in scanf conversion specifier to read a specific number characters from the input stream.

%2d%d first inputs integer with length of 2 then inputs the second integer.

* Output of the Program *

Skipping Characters in scanf –Example- Page 406Often it’s necessary to skip certain characters in the input stream. For example, consider reading date in the format:

(dd-mm-yyyy) 11-10-1999Each number in the date needs to be stored by discarding the dashes.

Dashes can be eliminated by including them in the format control string.scanf( "%d-%d-%d", &month, &day, &year );

This only eliminates/skips – not other characters. Also date can be entered as 10/11/1999

For such reasons, scanf provides the assignment suppression character *.

The assignment suppression character enables scanf to read any type of data from the input and discard it without assigning it to a variable.

scanf( "%d%*c%d%*c%d", &month, &day, &year );

%*c means read a character and discard it without assigning

Skipping in scanf (* Character) –Example- Page 407

Program uses the assignment suppression character %*c. So that scanf will input a character appearing in the input stream and discard it without storing in a variable.

* Output of the Program *

Page 412

a) 10000b)  Doesn’t print anthing. %s should be used to print a string. c)   Prints the number with %8.3f1024.988 e) Because printed numbers are positive, It will print space number then it will print +number.1000000+1000000f) 10 space reserved and only 9 characters uses to print the number  (1 Space )4.45E+002g) 10 space reserved and only 8 characters uses to print the number (2 Space)4.4e+002h) Trying to print a float number with %d is wrong. It will print something not meaningful. %f should be used. 274877907

Page 412

a) printf( "%s\n", 'Happy Birthday' ); printf( "%s\n", "Happy Birthday" ); Corrected!

b)    printf( "%c\n", 'Hello' ); printf( "%s\n", "Hello" ); Corrected!

c)    printf( "%c\n", "This is a string" ); printf( "%s\n", "This is a string" ); Corrected!

d) The following statement should print "Bon Voyage":printf( ""%s"", "Bon Voyage" ); printf("%s", "Bon Voyage" ); Corrected!

e) char day[] = "Sunday";printf( "%s\n", day[ 3 ] ); printf( "%s\n", day ); Corrected!

f) printf( 'Enter your name: ' ); printf("Enter your name: " ); Corrected!

g) printf( %f, 123.456 );printf("%f ", 123.456 ); Corrected!

h) The following statement should print the characters 'O' and 'K':printf( "%s%s\n", 'O', 'K' ); printf( "%c%c\n", 'O', 'K' ); Corrected!

i) char s[ 10 ];scanf( "%c", s[ 7 ] ); scanf( "%s", s ); Corrected!

Page 413

* Some Outputs *

Page 413

* Some Outputs  of the Program*

Out of Book Example (Triangular Texting)Write a program that takes a string from the screen then write it to screen in triangular form shape (10 times by shifting forward then coming back 9 times). If HKU is entered, then the printout of the program should be what you see on the right.**

* Another Output *