Thursday, December 10, 2009

3.3 ENTERING INPUT DATA- THE scanf FUNCTION

Input data can be entered into the computer from a standard input device by means of the C library function scanf.this function can be used to enter any combination of numerical values,single characters and strings.

In general terms, the scanf funstion is written as

scanf (control string,arg1,arg2,arg3,....,argn)

where control string refers to a string containing certain required formatting information,and arg1,arg2,arg3,....,argn are arguments that represent the the individual input data items(actually the arguments represent pointers that indicate the addresses of the data items within the computer's memory).

Some commonly used conversion characters for data input are

CONVERSION CHARACTER----------------------------------------------MEANING
c--------------------------------------------------------------data item is a single character
d--------------------------------------------------------------data item is a decimal character
e--------------------------------------------------------------data item is a floating point value
f--------------------------------------------------------------data item is a floating point value
g--------------------------------------------------------------data item is a floating point value
h--------------------------------------------------------------data item is a short integer
i---------------------------------------------data item is a decimal,hexadecimal or octal integer
o--------------------------------------------------------------data item is an octal integer
u------------------------------------------------------data item is an unsigned decimal integer
x-----------------------------------------------------------data item is a hexadecimal integer


Consider a C program that contains the following statements

#include

main()
{
int i;
float x;
char c;
.............
scanf("%d %f %c",&i,&x,&c);
or if
scanf("%3d %5f %c",&i,&x,&c);
.............
}

If the data items are entered as 10 256.875 T

when the program is executed ,then 10 will be assigned to i,256.875 will be assigned to x,T will be assigned to c

or if

field with is specified as in lin6
10 will be assigned to i,256.8 will be assigned to x and 7 will be assigned to c.The remaining two input characters 5 and T will be ignored.

%3d--->the first three digits will be assigned to i(1,0 and blank space)
%5f-->the next 5 digits will be assigned to x (2,5,6,.,and 8)
%c-->the next digit will be assigned to c(7)





No comments:

Post a Comment