home
C TUTORIALS

The Console Input/Output


The C programming language has no provision for receiving data from any of the input devices (like say keyboard, disk, etc.), or for sending data to the output devices (like say VDU, disk, etc.). We intend to learn how we manage I/O, inspite of the fact stated above, henceforth.


In the coming sections, we will learn about :


Types of I/O


There are numerous library functions available for I/O. These can be classified into three broad categories as below :


The Console I/O Functions


The screen and keyboard together are called a console. The console functions can be further divided into the following :


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. As discussed, scanf() and printf() fall under this category.
The syntax of printf() looks like :

printf ( "format string", list of variables ) ;
where the format string can contain :
The syntax of scanf() looks like :
scanf ( "format string", list of addresses of variables ) ;
For example :
scanf ( "%d %f %c", &c, &a, &ch ) ;
We have already used these functions in numerous examples before.
NOTE : Do not include escape sequences in the format string.


Unformatted Console I/O Functions


Under this category, we have functions that deal with either a single character or a string of characters.


Functions that deal with a single character

A weakness of scanf() is that we have to hit ENTER before the function can digest what we have typed. getch() and getche() are two functions that overcome this weakness. These functions return the character that has been most recently typed. The ‘e’ in getche( ) function means it echoes (displays) the character that you typed to the screen. As against this getch( ) just returns the character that you typed without echoing it on the screen.
getchar() works similarly and echoes the character that you typed on the screen, but unfortunately requires Enter key to be typed following the character that you typed.

main() { char ch; ch = getchar(); }

putch() and putchar() print a character on the screen. Their working is the same.
This is shown in the example:
main( ) { char c = 'C'; putch ( ch ); putchar ( ch ); putch ( 'A' ); putchar ( 'M' ); }
The output is CCAM


Functions that deal with a string of characters


Another weakness of scanf() is that it reads a string until it encounters a space. i.e. you cannot have strings having spaces input using this function. This is overcome by using gets() function. It is terminated when an Enter key is hit. Thus, spaces and tabs are perfectly acceptable as part of the input string.
The puts() function outputs a string to the screen.
The following program shows the use of these two functions:

main( ) { char footballer[40] ; puts ( "Enter name" ) ; gets ( footballer ) ; /* sends base address of array */ puts ( "Happy footballing!" ) ; puts ( footballer ) ; }