Tuesday, December 17, 2013

Chapter 3: Console Input/Output Operation



Console Input/Output Operation

Input and Output Statements
There are numerous library functions available for input-output functions. Depending upon the input and output devices used, these statements can be categorized into three groups as followings.

a)Console Input / Output Functions: These are functions used to receive input from keyboard and write output to VDU.
b)Disk Input / Output Functions: When the input-output operations are to be performed on a floppy or hard disk.
c)Port Input / Output Functions: For performing input-output functions on various ports.

Console Input/Output Functions
These library functions can be categorized as formatted and unformatted I/O functions. The basic difference between them is that the formatted functions allow the input read from the keyboard or output displayed on the VDU to be formatted as per our requirements. For example, if values of average marks and percentage are to be displayed on the screen, then the details like where this output should appear on the screen, how many spaces would be present between the two values, the number of places after the decimal point etc. can be controlled using formatted functions.

Console I/O functions can be classified into two categories:
i.   Formatted I/O Functions
ii. Unformatted I/O Functions

3.1 Formatted I/O Functions
The functions printf( ) and scanf( ) fall under this category.
3.1.1 Formatted Data Output Function-printf( )

The general form of printf( ) looks like this:
            printf("Format String", list of variables);
The format string can contains:
·Characters that are simply printed as they are
·Conversation specification that begins with a % sign
·Escape sequences that begin with a \ sign
For example:
            main( )
            {
               int avg=346;
               float per=69.3;
               printf("Average=%d\nPercentage=%f",avg,per);
               getch();
            }
How does printf() function interpret the contents of the format string? For this it examines the format string from left to right. So as long as it doesn't come across either a % or a \ it continues to dump the characters that it encounters, on 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, the moment 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 the format string is reached.

Some conversion specifier used with printf() statements
            Conversion specifier                                         Meaning
                        %d                                                       Convert to decimal integer
                        %f                                                        Convert to floating point number
                        %c                                                       Convert to Charcacter
                        %e or %E                                            Convert to scientific notation/double     
%s                                                       Convert to string of characters
%u                                                       Convert to unsigned decimal integer
                        %o                                                       Convert to octal number
                        %x or %X                                            Convert to hexadecimal number


3.1.2 Formatted Data Input Function-scanf( )
The general form of scanf() function is as follows:
            scanf("Format String", List of addresses of variables);
For example:
            scanf("%3d%0.2f%3c",&c,&a,&ch);
Note that we are sending addresses of variables(addresses are obtained by using '&' the address of operator) to scanf() function. This is necessary because the values received from the keyboard must be dropped into variables corresponding to these addresses. The values that are supplied through the keyboard must be separated by either blank(s), tab(s), or new line(s).

Some conversion specifier used with scanf() statements
            Conversion specifier                 Meaning
            %d                                           Data item is a decimal integer
            %f                                            Data item is a floating point value wiyhout exponent
            %e                                           Data item is a floating point value with exponent
            %c                                           Data item is a single character
            %s                                           Data item is a string variable
            %[^\n]                                      Data item is a string variable with space support

3.2 Unformatted Input-Output Functions
So far for input we have consistently used the scanf( ) function. However, for some situation, the scanf( ) function has weakness…you need to hit the enter key before the function can digest what you have typed. However, we often want a function that will read a single character the instant it is typed without waiting for the enter key to be hit. getch( ) and getche( ) are two functions which serve this purpose. These functions return the character that has been most recently typed. The 'e' in the getche( ) function means it echoes(displays) the character you typed to the screen. As against this getch( ) just returns the character you typed without echoing it on the screen. getchar( ) works similarly and echoes the character you typed on the screen, but unfortunately requires enter key to be typed following the character that you typed.
e.g.
            main( )
            {
               char ch;
               printf("\n Press any key to continue");
               getch( );        /* Will not echo the character */
               printf("\n Type any Character:");
               ch=getche( );
               printf("\n Type any Character:");
               getchar( );     /*Will echo character must be followed by enter key */
               printf("\n Continue Y/N:");
               getchar( );
            }
Output: Press any key to continue
            Type any Character:K
            Type any Character:W
            Continue Y/N:Y

putch( ) and putchar( ) print a single character on the screen. For these functions argument should be supplied. The following program illustrate this:
            main( )
            {
               char ch='A';
               putch(ch);
               putchar(ch);
               putch('Z');
               putchar('Z');
            }
Output: AAZZ
The limitation of putch( ) and putchar( ) is that they can output only one character at a time.

gets( ) and puts( ) functions
gets( ) receives a string from the keyboard. Why is it needed? Because scanf( ) function has some limitations while receiving string of characters, as the following program illustrates:
            main( )
            {
               char name[50];
               printf("Enter name: ");
               scanf("%s",name);
               printf("%s",name);
               getch( );
            }
Output: Enter name:Ram Chandra
             Ram
Surprised? Where did "Chandra" go? It never stored in the array name[ ], because the moment the blank was typed after "Ram" scanf( ) assumed that the name being entered has ended. So, to enter multi-word string from scanf( ) function extra trouble is required. The solution to this problem is to use gets( ) function. It gets a string from the keyboard and terminates when an Enter key is hit. Thus, spaces and tabs are perfectly acceptable as a part of the input string. More exactly, gets( ) gets a newline(\n) terminated string of characters from the keyboard and replaced the \n with a \o.
The puts( ) function works exactly opposite to gets( ) function. It outputs a string to the screen.
e.g.       main( )
            {
               char name[40];
               puts("Enter name:");
               gets(name);
               puts("Have a nice Day");
            }
Output: Enter name:
             Ram Chandra
             Have a nice Day

Why did we use two puts( ) functions to print "Have a nice Day" and "Ram Chandra"? Because, unlike printf( ), puts( ) can output only one string at a times. If we attempt to print two strings using puts( ), only the first one gets printed. Similarly gets( ) can be used to read only one string at a time.

Reading string with blank spaces using scanf( ) function
Example:
            main( )
            {
               char line[80];
                ……………
               scanf("%[  ABCDEFGHIJKLMNOPQRSTUVWXYZ]",line);
               …………….
               getch( );
            }
Here, in control string whit space and sequence of uppercase characters are enclosed in a square brackets. So, it can read the string containing blank spaces and uppercase letters.
If the string like  NEW YORK CITY is entered from the keyboard when the program is executed, the entire string will be assigned in the array 'line' since the string is comprised entirely of uppercase letters and blank spaces. If the string were written as New York City , then only the single character N would be assigned to 'line' because the second character 'e' is not included in the square brackets.

A variation of this feature which is often more useful is to precede the characters within the square brackets by a circumflex(i.e., ^). This causes the subsequent characters within the brackets to be interpreted in the opposite manner. Thus, when the program is executed, successive characters will continue to be read from the keyboard as long as each input character does not match one of the character enclosed within the brackets.
e.g.       main( )
            {
               char line[80];
               printf("Enter String:");
               scanf("%[^\n]",line);
               printf("%s",line);
               getch( );
            }
It will allow the user to enter the string of up to 80 characters until the user press the enter key. Here enter key will be interpreted as a new line character.

End of Chapter Three
[ Note: If you have any problems regarding this then you can post the problem in comment box. we will try to solve this here. Or if you know any solution, you can also help :) ]

No comments:

Post a Comment