scanf ( ) function:


The data can be entered into the computer from a standard input device by using library function scanf( ). The scanf( ) falls under the category of formatted console I/O functions.
            This function is used to enter numeric values, single character or strings, or some combination. As every function returns something similarly this function returns the number of data items that have been entered successfully.

General Syntax:

                        scanf (formatstring, arg1, arg2,………, argn);

Here, formatstring is a string that contains required formatting information. It consists of one or more character groups where each character group is used for each data item to be entered. Each character group begins with a percent sign (%) followed by a conversion character which indicates the type of the corresponding data item. Some common conversion characters are c,d,e,f etc.
        
    The arguments arg1, arg2,…… argn represent individual data items which can either be a variable name or an array name. The type of each data item should match the corresponding character group in control the control string. If variables are used then each variable name must be preceded by an ampersand (&) because the arguments are actually pointers which indicate where the data items are stored in computer’s memory. 

However, there is no need to put an ampersand before the array name. Each data item item is separated by comma.

For Example:
scanf(“%c”,&x);
scanf(“%d”,&y);
scanf(“%f”,&z);
scanf(“%s”,line);
Instead of all these statements, you can also write,
scanf(“%c%d%f%s”,&x,&y,&z,line);
Here “%c%d%f%s” is a format string enclosed in double quotes.

Program to show importance of scanf() ?
#include<stdio.h>
#include<conio.h>
main()
{
            int i;
            float j;
            short int x;
            long y;
            double z;
            clrscr ();
            scanf(“%4d%10f”,&i,&j);
            scanf(“%hd  %71d %151e”,&x,&y,&z);
            printf(“i= %d, j= %f”, i,j);
            printf(“x= %hd, y= %ld, z= %le”, x,y,z);
            getch();

    }

Previous                                                                                    Next

Powered by Blogger.