Tuesday, December 4, 2007

datainputsandoutputs

Data Input and Output
Preliminaries

So far, we've been using printf to do output, and we haven't had a way of doing any input. In this chapter, we'll learn a bit more about printf, and as well as other methods of handling input and output. In C all input/output operations are carried out through function calls like printf. These functions are collectively known as the standard I/O library.
We had already discussed in brief about the math library in Chapter 1, while using sqrt function. It may be recalled that we had also included a directive
#include
in The Fourth Program of Chapter 1. This directive tells the C compiler to include the contents of the file math.h, since the program uses the sqrt function, whose function prototype is defined in the math.h header file. Similarly, every program that uses a standard input/output statement, must contain the directive
#include
at the beginning of the program. It is to be noted that, in all the previous chapters we have never used this directive, even though some programs did use the printf function. The reason for this will be explained later when we discuss functions.
The file name stdio.h is an abbreviation for standard input-output header file. The directive #include tells the preprocessor to search for a file named stdio.h and place its contents in the program. The <> characters around the name tell the C preprocessor to look in the 'include' directory for the file stdio.h. However, if we had given the name as "stdio.h", it would tell the preprocessor to look in the current directory. This also means that we can set up libraries of our own routines and use them in our programs, a very useful feature of C.


Character Input and Output
getchar()
The simplest of all input/output operations is reading a character from the standard input device(typically the keyboard) and writing a character to the standard output device (typically the monitor screen). The most basic way of reading a character is using the getchar function. The getchar function is generally written as
variable - getchar()
where variable is a previously defined character variable. When this statement is encountered, the computer waits for a key-press. You can press any number of keys until finally you press the RETURN key When the return key is pressed the first character typed will be assigned to the variable on the left hand side.
Example:
The relevant parts of a program using the getchar function, is given below. #include
main()
{
char c;
c = getchar();
printf("%c", c); }
First the preprocessor directive for including the header file stdio.h is writtenwhere the getchar function prototype is defined. The first executable statementdeclares the variable c as a character-type variable. When this program is runthe getchar() function causes the program to wait. The cursor will blink askingfor keyboard input. You can type a series of characters and press the RETURNkey at the end. The program will then print the first character you typed on thekeyboard.
There are two other similar looking functions in C. They are the getch() and getche() functions. getch() like getchar() makes the program to wait for a keyboard input. As soon as a key is pressed the program continues. The getche() function behaves exactly like the getch() function. The only difference is that getche() echoes the character typed.
putchar()
For displaying single characters, the getchar function has a complementary function putchar. The putchar function is generally written as
putchar( variable)
where variable is a previously defined character variable. This statement causes the character contained in variable to be displayed on the terminal.
Example:
The relevant parts of a program using the putchar function, is given below. #include
main ()
{
char c;
c = 'A';
putchar(c); }
First the preprocessor directive for including the header file stdio.h is written, where the putchar function prototype is defined. The first executable statement declares the variable c as a character-type variable. The putchar function then

causes the current value of c to be transmitted to the standard output device. For example, if c has the value 'A', this statement will display A on the screen. If c contains the value V, this statement causes the cursor to move to the beginning of next line.
Formatted Input and Output
The two functions getchar and putchar that we have discussed are unformatted I/O functions. Now we are going to discuss two formatted functions viz. scanf and printf. The basic difference between these two categories of functions is that the formatted functions allow the input read from the keyboard and the output displayed on the screen to be formatted as per our requirements. For example, if values of name and marks of students 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 decimal places after the decimal point etc. can be controlled using formatted functions. However, in this chapter we are going discuss about reading and writing of single character, integer, and floating-point values. I/O functions for strings will be taken in the chapter on arrays.
scanf()
Formatted input refers to an input data that has been arranged in a particular format. For example, let's consider the data given below:
Anna 10 2.5
This line contains three pieces of data, arranged in a particular manner. This data has to be read conforming to the format of its appearance, that is, the first part has to be read as a string, the second part into an int variable and third part into a float variable. This can be done using the scanf function. The scanf function is generally written as
scanf( " control string ", argl, arg2,................ , argn )
where control string refers to a string containing certain required formatting
information, and argl, arg2, .............. , argn are arguments that specify the
address of locations where the data is to be stored.
The control string consists of individual groups of characters with one character group for each input data item. Each character group must begin with a percent sign(%). In its simplest form, a single character group will consist of the percent sign followed by a conversion character, which indicates the type of the corresponding data item. Within the control string, multiple character groups can be contiguous, or they can be separated by whitespace characters (blank spaces, tabs, or newline characters). A single white space between adjacent character groups will make the program more readable.
"%c %d %s %f" is more comfortable to read than "%c%d%s%f"
The following table lists the most frequently used conversion characters.

c- Read a single character
d- Read a decimal integer
e- Read a floating-point value
f- Read a floating-point value
g- Read a floating-point value
h- Read a short integer
i- Read a decimal, hexadecimal or octal integer
0- Read an octal integer
s- Read a string (the null character \0 will automatically be -added at the end)
u- Read an unsigned decimal integer
X- Read a hexadecimal integer
[?]- Read a string of word
(s)- Like printf() function, scanf() function also can have variable number of arguments.

Arguments of scanf() function are variable names preceded by an & symbol. An array name also can be used as an argument to scanf() function. When an array name is used as an argument, the preceding & symbol should be avoided, (we will discuss arrays in the subsequent chapters, for now it is sufficient to know that an array can be used to store a string, a list of integers or floating-point numbers etc.) The character groups in the formatting string reflect the data types of the argument list and there has to be perfect matching between the data type of the character groups in the formatting string and the argument variables. Consider the following program segment as an example.
char achar;
int aint;
char string[20];
float afloat;
scanf("%c %d %s %f", &achar, &aint, string, &afloat);
Example:
#include
main()
{
char code;
float price;
int qty;
scanf("%c %f %d", &code, &price, &qty);
}
In this example, the scant function has the control string "%c %f %d". It contains three character groups. The first character group %c, indicates that the first argument (code) represents a character value. The second character group %f, indicates that the second argument (price) represents a floating-point
value and the third character group %d, indicates that the third argument (qty) represents an integer value.
Note that all the three variables code, price and qty are preceded by ampersands within the scanf function.
When this program is executed, the data items can be entered from the standard input device in the following manner:
G 11.50 100
Then the character G will be assigned to code, the floating-point value 11.50 will be assigned to price and the integer value 100 will be assigned to qty.
Notice that the individual data items are entered on one line, separated by blank spaces. However, the data items could also be entered on separate lines, since newline characters are also white space characters. Thus, the data items could be entered as
G
11.50
100
Also note that scanf reads real numbers using the simple specification %f for both the decimal-point and exponential notation. Thus the input data
G 115E-1 100
would also assign G to code, 11.50 to price and 100 to qty.
Specifying Field Width with scanf()
The consecutive nonwhitespace characters that compose a data item is collectively called a field. It is possible to limit the number of such characters by specifying a maximum field width for that data item. To do so, an unsigned integer indicating the field width is placed within the control stung, between the percent sign (%) and conversion character.
The data item may be composed of fewer characters than the specified field width. However, the number of characters in the actual data item cannot exceed the specified field width. Any characters that extend beyond the specified field-width will not be read. Such leftover characters may be wrongly interpreted as the components of the next data item.
Example:
#include
main()
{
int x, y, z;
scanf("%3d %2d %4d", &x, &y, &z);
}
When this program is executed, three integer quantities have to be entered from the standard input device. Suppose the input data items are entered as
9 8 7
Then x would have the value 9, y would have the value 8 and z would have the value 7.
If the data items are entered as
987 65 4321 then x, y and z would have the values 987, 65 and 4321 respectively. Now suppose the data had been entered as
9876543210
Then the first 3 digits would be assigned to x, the next 2 digits to y, the next 4 digits to z and the last digit would not be read. Thus, x will have the 987, y will have the value 65 and z will have the value 4321. Moreover, the value 0 that is unread will be assigned to the first variable in the next scanf call.
Finally, suppose that the data has been entered as
987654321 0
The variables x, y and z would now have the values 987, 65 and 4321 respectively. The remaining digit 0, would be ignored, unless they were read by I a subsequent scanf statement.
Example:
#include
main()
{
int n;
float x;
char a;
scanf("%2d %6f %c", &n, &x, &a);
printf("%2d %6f %c", n, x, a);
}
When this program is executed, if the data items are entered as
9 123.6578 X
then the value 9 will be assigned to n, 123.65 will be assigned to x and the! character 7 will be assigned to a. The remaining two input characters, 8 and X, will be ignored.
Most versions of C also allow certain conversion characters in the control string to be preceded by a single-letter prefix, which indicates the length of the
corresponding argument. For example, an l( lowercase L) is used to either a signed or unsigned long integer argument, or a double precision argument. Similarly, an h can be used to indicate a signed or unsigned short integer argument.
Example:
#include
main()
{
short a;
long n;
double z;
scanf("%hd %ld %lf\ &a, &n, &z);
scanf("%2ho %6lx %14lf", &a, &n, &z);
}
In this example, the control string in the first scanf function indicates that the first data item will be assigned to a short decimal integer variable, the second will be assigned to a long decimal integer variable, and the third will be assigned to a double precision variable. The control string in the second scanf function indicates that the first data item will have a maximum field width of 2 characters and it will be assigned to a short octal integer variable, the second data item will have a maximum field width of 6 characters and it will be assigned to a long hexadecimal integer variable, and the third data item will have a maximum field width of 14 characters and it will be assigned to a double precision variable.
In this context, we should also know that, when the scanf reads a particular value, reading of the value will terminate as soon as the number of characters specified by the field width is reached(if specified) or until a character that is not valid for the value being read is encountered. For example, if a floating-point value is entered for an integer variable, then the fractional part may be stripped away. Also, scanf may skip reading further input.
Assignment Suppression
In most versions of C it is possible to skip over a data item without assigning it to any variable or array. To do so, the % sign within the appropriate control group is followed by an asterisk(*). This feature is referred to as assignment suppression.
Example :
#include
main()
{
int x, y, z; x=1; y=2; z=3;

Printf(Enter first set of numbers :"); scanf("%d %*d %d", &x. &y, &z); printf("x=%d, y=%d, z=%d\n", x, y, z);
printf("Enter second set of numbers :"); scanf("%d %*d %d %d", &x, &y, &z); printf("x=%d, y=%d, z=%d\n", x, y, z); }
When this program is executed, the following happens:
Enter first set of numbers :100 200 300
x=100y=300z=3
Enter second set of numbers :10 20 30 40
x=10y=30z=40
Here we have assumed that the input data entered is 100 200 300 10 20 30 40
Now let us try to understand this program. At first 3 integer variables x, y and z are declared and they are assigned values 1, 2 and 3 respectively. The first scanf statement is then executed. Since the scanf statement has 3 character groups, it expects 3 items of input data. However, notice that the second character group contains an asterisk(*), and thus the second input data item is not assigned to any variable. As a result, the first input data item is assigned to the first argument x, the second input data item is read but ignored, and the third input data item is thus assigned to the second argument y. The third argument is not assigned any value by the scanf statement, and as a result retains its earlier value. Thus the output of the first printf statement is
x=100y=300z=3
The second scanf statement, however, reads four input data items, and assigns it to three arguments while ignoring the second input data item. Thus all three arguments x, y and z are assigned values, even though the second input data item is ignored. The output of the second printf statement is thus
x=10y=30z=40
Example:
This example shows a more practical application of assignment suppression. #include
main()
{
int month, day, year;
printffEnter date of birth (mm/dd/ yyyy):"); scanf("%d %*c %d %*c %d", &month, &day, &year); printffYour birthday is on the %d-th day of the %d-month of year %c day, month, year);
}
This example basically reads a date entered by the user and then prints it. This shows an utility of assignment suppression. Since normally date is written in either mm/dd/yyyy or mm.dd.yyyy format, the program uses two dummy characters in the control string to eat away the delimiters V or'.' and enter the day, month and year parts in 3 different variables.
printf()
We have already used the printf function. This function can be used to output any combination of numerical values, single characters and strings. It is similar to the input function scanf, except that its purpose is to display data rather than to enter data into the computer. The printf function is generally written as
printf( " control string ", argl, arg2,.......... , argn )
where the control string indicates how many arguments follow and what their types are. It consists of three types of items:
• Characters that will be printed on the screen as they appear
• Format specifications that define the output format for display of each item
• Escape sequence characters like \n, \t and \b
The arguments argl, arg2,.......... , argn represent the individual data items. The
arguments can be written as constants, single variable or array names, or more complex expressions. Function references may also be included. In contrast to the scanf function, the arguments in a printf function do not represent memory addresses and therefore are not preceded by ampersands.
The following table lists the frequently used conversion characters. Note that some of the characters are interpreted differently than with the scanf function.

Character Conversion Meaning -c
Displays data item as a single character -d
Displays data item as a signed decimal integer -e
Displays data item as a floating-point value with an exponent -f
Displays data item as a floating-point value without an exponent -g
Displays data item as a floating-point value using either e-type or f-type conversion, depending on value; trailing zeros, trailing decimal point will not be displayed -i
Displays data item as a signed decimal integer -0
Displays data item as an octal integer, without a leading zero -s
Displays data item as a string -u
Displays data item as an unsigned decimal integer -X
Displays data item as a hexadecimal integer, without the leading -Ox

Example :
#inciude
main()
{
char a; float f; intx;
a='Z'; f=4.0;
x=1C0;
printf("%c %d %f %f", a, x, f, sqrt(f+1)); printf("%c%d%An", a, x, f);
printf("Character=%c\n lnteger=%d\n Real number=%f\n\n", a, x, f); printf("%e %e\n", f*x, sqrt(f+1 )/x); }
The output of this program will be : Z 100 4.000000 2.236068 Z1004.000000 Character=Z lnteger=100 Real number=4.000000
5.000000+002 2.236068-002
Let us understand each of the printf statements, one by one.
The first printf function has the formating string "%c %d %f %f ". It contains 4 character groups. The first character group %z, indicates that the first argument(a) represents a character. The second character group %d, indicates that the second argument(x) represents an integer. The third and fourth character groups, each of which is %f, indicates that the third and fourth argument^ and sa//f(f+1)) represent floating-point values. Also, note that the last argument is a function reference that has a numeric expression as an argument. Furthermore, none of the arguments are preceded by ampersands.
The output of the first printf statement is
Z 100 4.000000 2.236068
Notice that six decimal places are shown for each floating-point value. Also, note that the spaces between the data items is generated by the blank spaces that appear within the formating string within the printf statement. Since no blank spaces are specified in the control string of the second printf statement, the output of the second printf is as follows
Z1004.000000
Also, notice the newline character(\n) in the printf statements.
Thus the output of the third printf statement is
Character=Z
lnteger=100 Reai number=4.000000
The fourth printf makes use of the e-type conversion character and has the following output
5.000000+002 2.236068-002
The following table lists the escape sequences commonly used in the printf statement.

Escape Sequence
Meaning
\t -Displays horizontal tab
\v -Displays vertical tab
\n -Takes the cursor to the beginning of the next line
\" -Displays quotation mark(")
\\ -Displays backslash(\)
Specifying Field Width with printf()
A minimum field width can be specified by preceding the conversion character by an unsigned integer. If the number of characters in the corresponding data item is less than the specified field width, then the data item will be preceded by enough leading blanks to fill the specified field. However, if the number of characters in the data item exceeds the field width, then additional space will be allocated to the data item, so that the entire data item is displayed. This is just the opposite of the field width indicator in the scant function, which specifies a maximum field width.
Example :
Format printf("%d". 12345)
printf("%3d" .12345) printf("%8d" .12345)
printf("%f", 123.45)
printf("%4f". 123.45)
printf("%10f'.123.45)
Output
h 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
In case of floating point numbers, it is possible to even specify the number of digits to be displayed after the decimal point. The value, when displayed is rounded to the desired number of decimal places. Furthermore, it is possible to force the printing to be left justified by placing a minus sign directly after the % character. It is also possible to pad leading blanks with zeros by placing a zero before the field width specifier.
Example:
Format
printf("%-8d", 12345) printf("%08d", 12345) printf("%.2f\123.45678)
printf("%10.2f',123.45678) printf("%-10.2f', 123.45678)
printf("%10.2e'M 2.3934)
printf("%10.4f",12.3934)
Output
printf("%-8d", 12345) --1 2 3 4 5
printf("%08d", 12345) --0 0 0 1 2 3 4 4
printf("%.2f\123.45678)--1 1 1 2 3 I • I 4 I 5 I
printf("%10.2f',123.45678) --1 2 3 4 5
printf("%-10.2f', 123.45678)--1 2 3 4 5
printf("%10.2e'M 2.3934)--1 2 4 E + 0 1
printf("%10.4f",12.3934)--1 2 3 9 3 E + 0 1
The following table lists the flags that are commonly used to affect the appearance of the output. Flag 0
Meaning
Data item is left-justified within the field
A sign(+ or -) will precede each signed numerical data item; without this flag, only negative data items are preceded by a sign
Causes leading zeros to appear instead of leading blanks
A blank space will precede each positive signed 1 '(blank space) numerical data item; this flag is overridden by the + flag if both are present
# Causes octal and hexadecimal data items to be preceded(with o- and x- type by 0 and Ox respectively
conversion)
# Causes a decimal point to be present in all floating-point(with e-, f- and g- numbers, even if the data item is a whole number; alsotype conversions) prevents truncation of trailing zeros in g-type conversion