input and output
Input and Output

Introduction to Input and Output

Reading, processing, and writing of data are the three essential functional functions of a computer program input and output operations. Most programs take some data as input and display the processed data, often known as information or results, on a suitable medium. So far we have seen two methods of providing data to the program variables. One method is to assign values to variables through the assignment statements such as x=5; a=0; and so on. Another method is to use the input and out function scanf which can read data from a keyboard. We have used both the methods in most of our earlier example programs. For outputting results we have used extensively the fuction printf which sends results out to a terminal.

Unlike other high-level languages, C does not have any built-in input/output statements as part of its syntax. All input/output operations are carried out through function calls such as printf and scanf. There exist several functions that have more or less become standard for input and output operations in C. These functions are collectively known as the standard input and output library. In this chapter we shall discuss some common Input and Output functions that can be used on many machines without any change. However, one should consult the system reference manual for exact details of these functions and also to see what other functions are available.

#include <math.h>

Where a math library function cos(x) has been used. This is to instruction the compiler to fetch the function cos(x) from the math library, and that it is not a part of C language. Similarly, each program that uses a standard input/output function must contain the statement

#include <stdio.h>

at the beginning. However there might be exceptions. For example, this is not necessary for the functions printf and scanf which have been defined as a part of the C language.

Reading a Character

The simplest of all input/output operations is reading a character from the ‘standard input’ unit (usually the keyboard) and writing it to the ‘standard output’ unit (usually the screen). Reading a single character can be done by using the function getchar.

variable_name=grtchar();

variable_name is a valid C name that has been declared as char type. When this statement is encountered, the computer waits until a key is pressed and then assigns this character as a value to getchar function. Since getchar is used on the right hand side of an assignment statement, the character value of fetchar is in turn assigned to the variable name on the letf.

char name;
name = getchar();

Will assign the character ‘H’ to the variable name when we press the key H on the keyboard. Since getchar is a function, it requires a set of parentheses as shown.

The program displays a question of YES/NO type to the user and reads the user’s response in a single character (Y or N). If the response is Y or Y, it outputs the message My name is BUSY BEE

Program
  #include <stdio.h>
  main()
  {
     char answer;
     printf("Would you like to know my name?\n");
     printf("Type Y for YES and N for NO: ");
     answer = getchar(); /* .... Reading a character...*/
     if(answer == 'Y' || answer == 'y')
        printf("\n\nMy name is BUSY BEE\N");
     else
     printf("\n\nYou are good for nothing\n");
  }
 Output
     Would you like to know my name?
     Type Y for YES and N for NO: Y
     Would you like to know my name?
     Type Y for YES and N for NO: n
     You are good for nothing

The getchar function may be called successively to read the characters contained in a line of text. For example, the following program segment reads characters from keyboard one after another untile the ‘Return’ key is pressed.

The getchar() function accepts any character keyed in. This includes RETURN and TAB . This means when we enter single character input, the newline character is waiting in the input queue after getchar() returns.

Note : We shall be using decision statements like if, if…else and while extensively in this chapter. They are discussed in detail next chapter.

This program receives a character from the keyboard and tests whether it is a latter or digit and prints out a message accordingly. These tests are done with the help of the following functions:

isalpha(character)
isdigit(character)

for example, isalpha assumes a value non-zero (TRUE) if the argument character contains an alphabet; otherwise it assumes 0 (FLASE). Similar is the case with the function isdigit.

Program:
         #include <stdio.h>
         #include <ctype.h>
         main()
          {
             char character;
             printf("Press any key\n");
             character = getchar();
             if (isalpha(character) >0)/* Test for letter */
                 printf("The character is a letter.");
             else
                 if (isdigit (character) >0)/* Test for digit */
                     printf("The character is a digit is a digit.");
             else 
                     printf("The character is not alphanumeric.");
          }
Output
          Press any key
          h
          The character is a letter.
          Press any key
          5
          The character is a digit.
          Press any key
          *
          The character is not alphanumeric.

C supports many other similar functions, which are given in table in next. These character functions are contained in the file ctype.h and therefore the statement #include <ctype.h> must be included in the program.

Writing a Character – input and output

Like getchar, there is an analogous function putchar for writing characters one at a time to the terminal. It takes the form as shown below: putchar (variable_name);

where variable_name is a type char variable containing a character. This statement display the character contained in the variable_name at the terminal.

answer = 'Y' ;
putchar (answer);

will display the character Y on the screen. The statement putchar (‘\n’); would cause the cursor on the screen to move to the beginning of the next line.

The program uses three new functions: islower, toupper, and tolower. The function islower is a conditional function and takes the value TRUE if the argument is a lowercase alphabet; otherwise takes the value FALSE. The function toupper converts the lowercase argument into an uppercase alphabet while the function tolower does the reverse.

Formatted Input

Formatted input to an input data that has been arranged in a particular format. For example, consider the following data: 15.75 123 John

This line contains three pieces of data, arranged in a particular form. Such data has to be read conforming to the format of its appearance. For example, the first part of the data should be read into a variable float, the second into int, and the third part into char. This is possible in C using the scanf function. (scanf means scan formatted)

The control string specifies the field format in which the data is to be entered and the argument arg1, arg2,… argn specify the address of locations where the data is stored, Control string and arguments are separted by commas.

  • Field (or format) specifications, consisting of the conversion character % a data type character (or type specifier), and an optional number, specifying the field width.
  • Blanks, tabs, or newlines.
  • Blanks, tabs and newlines are ignoerd. The data type character indicates the type of data is to be assigned to the variable associated with the corresponding argument. The field width specifier is optional. The discussions that follo will clarify these concepts.

Inputting Integer Numbers – input and output

The field specification for reading an integer number is : % w sd

The percentage sign (%) indicates that a conversion specification follows. w is an integer number that specified the field width of the number to be read and d, know as data type character, indicates that the number to be read is in interger mode. Consider the following example: scanf (“%d %5d”, &num1, &num2);

The variable num1 will be assigned 31 (because of %2d) and num2 will be assigned 426 (unread part of 31426). The value 50 that is unread will be assigned to the first variable in the next scanf call. This kind of error may be eliminated if we use the field specifications without the without the field width specifications. That is the statement scanf(“%d %d”, &num1, &num2);

Input data items must be separated by spaces, tabs or newlines, punctuation marks do not count as separators. When the scanf function searches the input data line for a value to be read, it will always bypass any white space characters.

What happens if we enter a floating point number of an integer? The fractional part may be stripped away! Also, scanf may skip reading further input.

The data type character d may be preceded by ‘I’ (letter ell) to read long integers and h to read short integers.

Note : we have provided white space between the field specifications. These spaces are not necessary with the numeric input, but it is a good practice to include the.

The first scanf requests input data for three integer value a,b and c, and accordingly three values 1,2 and 3 are keyed in. Because of the specification %*d the value 2 has been skipped and 3 is assigned to the variable b. Notice that since no data is available for c, it contains garbage.

The second scanf specifies the format %2d and %4d for the variables x and y respectively. Whenever we specify field width for reading integer numbers, the input numbers sholud not contain more digits that the specifid size. Otherwise, the extra digits on the right hand side will be truncated and assigned to the next variable in the list.

Note : It is legal to use a non whitespace character between field specification. However, the scanf expects a matching character in the given location.

Inputting Real Numbers

Unlike inteher numbers, the field width of real numbers is not to be specified and therefore scanf reads real numbers using the simple specification %f for both notation, namely, decimal point notation and exponential. scanf(“%f %f %f”,  &x, &y, &z); with the input data 475.89 43.21E-1 678

will assign the value 475.89 to x, 4.321 to y, and 678.0 to z. The input field specifications may be separated by any arbitrary blank spaces. If the number to be read is of double type, the specification should be %if instead of simple %f. A number may be skipped using %*f specification.

Inputting Character Strings

We have already seen how a single character can be read from the terminal using the getchar function. The same can be achieved using the scanf function also. In addition, a scanf function can input strings containg more than one character. Following are the specifications for reading character strings: %ws or %wc

The corresponding argument should be a pointer to a character array. However, %c may be used to read a single character when the argument is a pointer to a char variable. when we use %wc for reading a string, the system will wait until the w character is keyed in.

Reading Mixed Data Types

It is possible to use one scanf statement to input a data line containing mixed mode data. In such cases care should be exercised to ensure that the input data items match the control specifications in order and type. When an attempt is made to read an item that does not match the type expected, the scanf function does not read any further and immediately returns the value read. The statement

scanf ("%d %c %f %s", &count, &code, &ratio, name);

Correctly and assign the values to the variables in the order in which they appear. Some systems accept integers in the place of real numbers and vice versa, and the input data is converted to the type specification in the control string.

Note : A space before the %c specification in the format string in necessary to skip the white space before p.

Detection of Errors in Input

When a scanf function completes reading its, it returns the value of number of items that are successfully read. This value can be used to test whether any errors occurred in reading the input. For example the statement

scanf("%d %f %s, &a, &b, name);

will return the value 3 if the following data is typed in:

20 150.25 motor

and will return the value 1 if following line is entered

20 motor 150.25

This is because the function would encounter a string when it was expecting a floating point value, and would therefore terminal its scan after reading the first value.

The function scanf is expected to read three items of data and therefore, when the values for all the three variables are read correctly, the program prints out their values. During the third run, the second item does not match with the type of variable and therefore the reading is terminated and the error message is printed. Same is the case with the fourth run.

In the last run, although data items do not match the variables, no error message has been printed when we attempt to read a real number for an int variable, the integer part is assigned to variable and the truncated decimal part is assigned to the next variable.

  1. h for short integers
  2. l for long integers or double
  3. L for long double

Points to Remember While Using scanf – input and output

If we do not plan carefully, some ‘crazy’ things can heppen with scanf. Since the Input and output are not part of C language, they are made available either as a separate module of the C library or as a part of the operating system (like UNIX). New feature are added to these routines from time to time as never versions of systems are released. We should consult the system referance manual before using these routines.

  1. All function arguments, except the control string must be pointers to variables.
  2. Format specifications contained in the control string should match the arguments in order.
  3. Input data items must be separated by spaces and must match the variables reciving the input in the same order.
  4. The reading will be terminated, when scanf encounters a ‘mismatch’ of data or a character that is not valid for value being read.
  5. When searching for a value, scanf ignores line boundaries and simply looks for the next appropriate character.
  6. Any under data items in a line be considered as part of the data input to the next scanf call.
  7. When the field width specifier w is used, it should be large enough to contain the input data size.

Rules for scanf

  • Each variable to be read must have a filed have a specification.
  • For each field specification, there must be a variable address of proper type.
  • Any non-whitespace character used in the formated string must have a matching character in the user input.
  • Never end the format string with whitespace. It is a fatal error!

Read more : Microprocessor