C      PROGRAMMING

INPUT/OUTPUT

          C simply has no provision for receiving data from any of the input devices (say keyboard, floppy) or for sending data to the output devices (say VDU, floppy etc.). Though C has no provision for I/O, it of course has to be dealt with at some point or the other. There is not much use writing a program that spends all it's time telling itself a secret. Each operating system has its facility for inputting and outputting data from and to the files and devices. There are numerous library functions available for I/O. These can be classified into three broad categories:

  1. Console I/O functions - functions to receive input from keyboard and write output to VDU.
  2. Disk I/O functions - functions to perform I/O operations on a floppy disk or hard disk.
  3. Port I/O functions - functions to perform I/O operations on various ports.

Console I/O Functions:

Console I/O functions can be further classified.

Console Input/Output functions

 

 

 

   Formatted functions

 

  Unformatted functions

Type 

Input

Output

 

Type 

Input

Output

char 

scanf()

printf()

 

char

 getch()

putch()

 

 

 

 

 

 getchar()

putchar()

 

 

 

 

 

getche( )

 

int 

scanf()

printf()

 

int

-

-

float  

scanf()

printf()

 

float

-

-

string    

scanf()

printf()

 

string

gets()

puts()

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

The library implements a simple model of text input and output. A text consists of a sequence of lines, each ending with a newline character. If the system doesn't operate that way, the library does whatever is necessary to make it appear as if it does. For instance, the library might convert carriage return and linefeed to newline on input and back again on output.

getchar( ):

The simplest input mechanism is to read one character at a time from the standard input, normally the keyboard, with getchar( ).

int getchar(void);

getchar( ) returns the next input character each time it is called, or EOF when it encounters, end of file. The symbolic constant EOF is defined in . The value is typically -1, but tests should be written in terms of EOF so as to be independent of the specific value.

putchar( ):

The function :

int putchar(void);

is used for output. Putchar(c) puts the character c on the standard output, which is by default, the screen. Putchar() returns the character written, or EOF if an error occurs.

#include <stdio.h>
#include<ctype.h>
main()
/* Convert input to lower case */
{
int c;
while ((c = getchar()) != EOF)
putchar(tolower(c ));
return 0;
}

printf( ):

The output function printf() translates internal values to character.

printf(char format, arg1, arg2, ... )

The format string can contain:

  • Characters that are simply printed as they are.
  • Conversion specification that begins with a % sign.
  • Escape sequences that begins with a \ sign.

Printf() converts, formats, and prints its arguments on the standard output under the control of the format. It returns the number of characters printed. The format string contains two types of objects - ordinary characters, which are copied to the output stream, and conversion specifications, each of which causes conversion and printing of the next successive argument to printf(). Each conversion specification begins with % and ends with a conversion character. Between the % and the conversion character there may be, in order:

  • A minus sign, which specifies left adjustment of the converted argument.

·         A number that specifies the minimum field width. The converted arguments will be printed in a field at least as wide as the specified minimum. If necessary, it will be padded on the left (or right, if left adjustment is called for) to make up the field width.

  • A period (.) separates the field width from the precision.

·         A number, i.e., the precision that specifies the maximum number of characters to be printed from a string, or the number of digits after the decimal point of a floating-point value, or the minimum number of digits for an integer.

If the character after the % is not a conversion specification, the behavior is undefined.

 

sprintf( ):

This function works similar to the printf( ) function except for one small difference. Instead of sending the output to the screen as printf( ) does, this function writes the output to an array of characters. For example, look at the following problem:

#include<stdio.h>
main( )
{

int i = 10 ;
char ch = 'A' ;
float a = 3.14 ;
char str[20] ; /* Array of characters */
printf ( "%d %c %f", i, ch, a) ;
sprintf ( str, "%d %c %f", i, ch, a) ;
printf ( "%s", str ) ;

}

In this program, the printf( ) prints out the values of i, ch and a on the screen, whereas sprintf( ) stores these values in the character array str. Since the string str is present in memory, what is written into str using sprintf( ) doesn't get displayed on the screen. Once str has been built, its contents can be displayed on the screen. In our program this is achieved by the second printf( ) statement.

scanf( ):

scanf( ) allows us to enter data from the keyboard that will be formatted in a certain way. The general form of scanf( ) statement is as follows:

scanf("%d %f %c",&c,&a,&ch);

Note that we are sending the addresses of variables (addresses are obtained by using & - 'address of' operator) to scanf( ) function. This is necessary because the values received from 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 newline(s). Do not include these escape sequences in the format string.

Following is the list of conversion characters that can used with printf( ) and scanf( ) function.

Data type

 

 

Conversion character

Integer

 

short signed

%d or %I

 

 

short unsigned

%u

 

 

long signed

%ld

 

 

long unsigned

%lu

 

 

unsigned hexadecimal

%x

 

 

unsigned octal

%o

Real

 

float

%f

 

 

double

%lf

Characters

 

signed char

%c

 

 

unsigned char

%c

string

 

 

%s

 


gets( ):

The gets( ) function receives a string from the keyboard. The scanf( ) function has some limitations while receiving a string of characters because the moment a blank character is typed, scanf( ) assumes that the end of the data is being entered. So it is possible to enter only one word string using scanf( ). To enter multiple words in to the string, the gets( ) function can be used. Spaces and tabs are perfectly accepted as part of the string. It is terminated when the enter key is hit.

gets(variable name);

For example:

gets(name);

puts( ):

The puts( ) function works exactly opposite to gets( ) function. It outputs a string to the screen. Puts( ) can output a single string at a time.

puts(variable name);

For example :

#include<stdio.h>
main( )

{

char name[40];
puts("Enter your name");
gets(name);
puts("Your name is");
puts(name);

}

Escape Sequence:

The newline character '\n' when inserted in a printf( )'s format string, takes the cursor to the beginning of the next line. The newline character is an 'escape sequence', so called because the backslash symbol (\) is considered an 'escape' character : it causes an escape from the normal interpretation of a string, so that the next character is recognised as one having a special meaning.

The following example shows usage of '\n' and a new escape sequence '\t' called 'tab'.

main( )

{

printf("when \t there \t is \t will\n there \t is \t a \t way");

}

Esc. Seq.

Purpose

Esc. Seq.

Purpose

 

 

 

 

\n

New line

\t

Tab

 

 

 

 

\b

Backspace

\r

Carriage return

 

 

 

 

\f

Form feed

\a

Alert

 

 

 

 

\'

Single quote

\"

Double quote

 

 

 

 

\\

Backslash

 

 

 

 

 

 

 

 

 

 

The first few of these escape sequences are more or less self- explanatory. '\b' moves the cursor one position to the left of its current position. '\r' takes the cursor to the beginning of the line in which it is currently placed. '\a' alerts the user by sounding the speaker inside the computer. '\f' advances the computer stationery attached to the printer to the top of the next page. Characters that are ordinarily used as delimiters - the single quote, double quote are preceded by backslash in order to print them.

Thus, the statement,

printf("when \t there \t is \t will\n there \t is \t a \t way");

will print

      when      there    is     will
          there      is    a    way 


 


 

  HOME

<<PREVIOUS                NEXT>>

Want Easy lessons and exercises!! Then search here:

Google
Web www.poombatta.com



© poombatta.com