Wednesday, November 2, 2011

Formatted Console I/O Functions in C programming language

As can be seen from Figure 11.1 the functions printf( ), and scanf( ) fall under the category of formatted console I/O functions. These functions allow us to supply the input in a fixed format and let us obtain the output in the specified form. Let us discuss these functions one by one.
We have talked a lot about printf( ), used it regularly, but without having introduced it formally. Well, better late than never. Its general form looks like this...

printf ( "format string", list of variables ) ;

The format string can contain:
(a) Characters that are simply printed as they are
(b) Conversion specifications that begin with a % sign
(c) Escape sequences that begin with a \ sign
For example, look at the following program:

main( )
int avg = 346 ;
float per = 69.2 ;
printf ( "Average = %d\nPercentage = %f", avg, per ) ;

The output of the program would be...
Average = 346
Percentage = 69.200000

How does printf( ) function interpret the contents of the format string. For this it examines the format string from left to right. So long as it doesn’t come across either a % or a \ it continues to dump the characters that it encounters, on to the screen. In this example Average = is dumped on the screen. The moment it comes across a conversion specification in the format string it picks up the first variable in the list of variables and prints its value in the specified format. In this example, the moment %d is met the variable avg is picked up and its value is printed. Similarly, when an escape sequence is met it takes the appropriate action. In this example, the moment \n is met it places the cursor at the beginning of the next line. This process continues till the end of format string is not reached.

No comments:

Post a Comment