Data Input And Output Function
For data input and output C provides a collection of library functions such as getchar, putchar, scanf, printf, gets and puts. These functions permit the transfer of information between the computer and standard input/output devices. Thestandard
input and output devices like Keyboard and Monitor are treated as files
by the UNIX system. UNIX is consistent in treating files, since it
considers a file to be a stream of bytes. Text input or output,
regardless from where it originates or where it goes to, is dealt with
as stream of characters. A textstream
is a sequence of characters divided into lines; each line consists of
characters followed by a newline. All input or output functions conform
to this model.
The first two lines of the program in Example 1.1 contain following two statements.
Although those two lines look likeprogram statements, they are not part of a function body and do not end with a semicolon, as program statements must. Instead, they start with a hash sign (#), and are called preprocessor directives. While program statements are instructions to the computer, a preprocessor directive, is an instruction to the compiler itself. A part of the compiler called the preprocessor deals with these directives before it begins the real compilation process.
The preprocessor directive #include tells the compiler to insert another text file into your source file. In fact, the #include directive is replaced by the contents of the file indicated. The filenames stdio.h and math.h are examples of header files. These header files contain definitions of standard C utility programs and without these declarations the compiler will not allow the usage of commonly used standard input and output functions such asgetchar, putchar, scanf and printf, etc. The definitions of these functions are included in the stdio.h file. Thus reference to any such function inside the program requires the corresponding header file to be included using #include preprocesser directive. The symbols <>, that enquote the header filename indicates that the header file is located under /usr/include directory.
4.2 THE SINGLE CHARACTER INPUT(getchar) AND OUTPUT (putchar) FUNCTIONS
The getchar and putchar are two standard library functions for reading one character at a time from a keyboard (standard input device such as keyboard) or writing a character to the monitor (standard output device e.g monitor). Each time the getchar function is called, it reads the next character from the
text stream and returns this character as its value. The character normally comes from the file associated with the keyboard.The function returns the symbolic constant EOF(for end of file) which typically stores the value -1, when there is no input. The EOF is an integer defined in stdio.h header file.
Example 4.1 :
The function putchar displays a character each time the function is called; it prints the content of integer c as a character, usually on the screen.
4.3THE scanf FUNCTION
The function scanf is used to input data from the standard input device. In general, the scanf function is written as
where the refers to a string containing required formatting information and arg1, arg2, ..., argn are individual data items. Actually these arguments represent pointers that indicate the addressesof the data items in the computer’s memory.
One group of characters forms one control group for each data item in the list of arguments supplied to the scanf function. Each control group begins with the character percentage (%) followed by a conversion character which indicates the type of the corresponding data item. Similar control string is also used with the printf function to be discussed later. The meaning of the conversion characters for input /output is given in the table below,
Commonly used conversion characters for input/output:
Table 4.1 : Conversion character set.
In scanf each variable name (not of pointer type) must be preceded by &. However array names or pointer data types must not begin with ampersand.
Example 4.2 :
scanf(“%s%d%f”, name, &rollno, &grade);
Note the variable name being a string (an array of characters) is not preceded by &, but the numerical variables rollno andgrade are preceded by &. Whileproviding data values they must be separated by whitespace character e.g. blank, new line etc.
Example 4.3 :
int x,y,z ;
float u,v,w ;
scanf (“%3d,%4f,%c”, &x, &u, &c)
If the data items provided are 10540.36A, then the variablesget valuesx = 105,u = 40.3,c = 6; note the character A is ignored. This is because the field width for u is 4 which can accommodate 40.3. The remaining character 6 is assigned to c.
3.Consider a C program with thefollowing declaration:
Write an appropriate scanf function to read i, j and k, assuming
a) The values of all of them aredecimal integers.
b) The values for ka decimal integer, i an octal integer and j a hexadecimal integer.
c) The values for i and j will be octal numbers and k will be an hexadecimal integer.
4. Interpret the meaning of the control string in each of the following scanf functions:
a) scanf (“%10d %3hd %14f”, &a, &b, &c);
b) scanf (“ %5ho %6hu%7tu”, &a, &b, &c);
c) scanf (“%10d %13f %16e”, &a, &b, &c);
d) scanf (“%7d %6d %10 lf”, &a, &b, &c );
5.Consider a C program havingthe following declarations:
int i, j;
Write a scanf function for each of the following groups of variables that will allow a corresponding set of data items to be read into respective variables. Assume that all integers will be read in as decimal quantities.
(a) i, j,d and x(c) il, u,s and c
(b) i,j, x and u(d) c, d,and s
6.A C program contains the following variable declarations:
int i, j;
Write a suitable scanffunction for reading data according to each of the following specifications. Assume that all integers will be read in as decimal quantities.
(a) Assuming that each integer data does not exceed five characters, the floating -point data does not exceed eight characters, and the double-precision data does not exceed 16 characters, enter values for i, j, x and d.
(b) The values fori, il, j, x and u are to be entered, assuming that each integer quantity does not exceed four characters, the long integer does not exceed 18 characters, and the floating-point data does not exceed 9 characters.
(c) The values for i, u and c, are to be read assuming that each integer data does not exceed five characters.
(d) The values for c, x, d and s,are to be read assuming that the floating-point data does not exceed eight characters, the double-precision data does not exceed 16 characters and the short integer does not exceed four characters.
7.Consider a C program with the following declarations.
int a, b;
float x, y;
Suppose the following values are to the entered and assigned to a, b, x and y respectively.
16,-43, 6. 391, - 43 ´ 107
Show how the input data shouldbe entered foreach of the following scanf functions.
a) scanf (“%d %d %f %f”, &a, &b, &x, &y);
b) scanf (“%d %d %e%e”,&a, &b, &x, &y);
c) scanf (“%3d %3d %6f %7e”, &a, &b, &x, &y);
d) scanf (“%2 d %3d %7f %8e”, &a, &b, &x, &y);
This function is used to output data onto a standard output device.
The syntax is
printf (, arg1,arg2,.... argn);
where the meaning of the control string is the same as in scanf.However, unlike scanf, the variable names in arg1,...........,argn are not to be preceded by the & symbol.This is because printf is expected to only output the values of these variables and not to modify their content.
Example: 4.4 :
printf(“Our first program in C\n”);
printf(“The value of n = %d\n”,n); /* note usage of format specifier */
printf(“Give an integer :”);
scanf(“%d”,&n);/* note usage of & before n */
fflush(stdin);/* flushes the stdin buffer */
printf(“The integer read is %d\n”,n); /* note no & symbol is present */
float x = 2.0;
inty = 4;
charc = ‘A’;
printf (“%f%d%c\n”, x,y,c);
The printf statement given above will print the data values x, y, and c as follows,
followed by a blank line(due to \n).
This printf statement has the disadvantage that it may cause output values to be printed without any intermediate spaces. To introduce blank spaces in between the output values use the following printf statement which include blanks in the control string.
printf(“%f %d %c \n”, x,y,c).
Note that unlike in scanf, the variables in the printf statement are not preceded by the & character.
The following printf statement can be used to print data values according to a specific format,
printf (“%6.2f%2d %c \n”,x,y,c);
If x,y and c had values 453.7869, 243 and B assigned to them respectively, this printf statement will print 453.79, 243 and B.Note that due to the precision specification the floating point variable has been rounded to fit the specified field width.Leading blanks may be introduced to fill the minimum field width (usually 7 character). Since the field width specified for y is too small 2d as compared to the specified field width supported for integer data items (e.g. 8 digits). The entire integer value would be displayed preceded by leading blanks to fill the specified width.
Here is a program that illustrates the use of precision feature with floating point numbers. The character ‘*’ in the format specification helps in understanding the width of the display.
Example 4.5 :
printf(“*%-15f*\n”,f);/* ‘-’ character changes the default alignment*/
The above program displays the following output :
8.A C program contains the following declaration:
int i, j, k;
Write a printf function for printing each of the following groups of variables or expressions.
(a) i, j and k,with a minimum field of four characters per variable.
(b) (i + j), (i - k), with a minimum field width of six characters per expression.
(c) sqrt (i / j), abs (i * k), with a minimum field width of eight characters for the first expression and eight characters for the second expression.
9.A C program contains the following declarations:
int i, j, k;
Write a printf function for displaying each of the following groups of variables or expressions.
(a) i, j and k(b) (i + j), (i *- k)(c) sqrt(i / j), abs(i - k)
4.5SAMPLE C PROGRAMS
The following examples illustrate the different ways to input a string of characters and to display them.
Example 4.6 :
/* program takes string as input */
printf(“Enter your name :”);
scanf(“%s”,anyname);/* Note that a string variable does not need to be prefixed by ‘&’ symbol */
printf(“%-20s”,anyname); /* ‘-’ before 20s in format specification prints name left justified within 20 characters long width */
In the above example if the name is entered with embedded space then the variable anyname will be assigned with all characters till the space, since space will terminate the input stream. In this example, if input given is,
char in_string, out_string=“IIT-Dedicated to the Service of The Nation”;
printf(“Enter a string :”);
scanf(“%[^\n]s”,in_string); /* Statement A */
printf(“Enter a string :”);
In the above program, the statement A will allow input of any characterexcept the newline character (\n). The ^ symbol before ‘\n’ indicates that the input stream will be terminated as soon as the user presses the enter key. Most importantly, the user can also input embedded spaces. The statement B allows input of capital alphabets and spaces only. A preceding ^ in the format specification would have restricted the input to the characters other than specified within the square brackets. The format specification used with the printf statements that follow will display the following strings on the screen.