Computer Science 1511
Computer Science I

Laboratory Assignment 4
Formatted Input (5 points)
Due at the end of Lab


This lab will familiarize you with reading input so that the user will find it easy to enter the correct input that is required for the program. The standard formatted input function in C is scanf.In this lab you will also learn how to avoid certain common errors that you might perform while using scanf.

Like printf, scanf also consists of two parts: a format string that describes the data and an address list that identifies where data are to be placed in memory. The scanf statement is of the form:

      scanf(Format_String, Address_List);

The format string is enclosed in a set of quotation marks ("...") and contains one or more field specifications that describe the data types and indicate any special formatting rules and/or characters. Each field specification (which describes the data to be input from the user) begins with a percent sign (%) and describes exactly one field or variable. The first specification matches the first parameter, the second matches the second parameter, and so on.

Scanf requires that the variables in the address list be represented by their addresses. To specify an address, prefix the variable name with the address operator using the ampersand character (&). For example, &x corresponds to the address of the variable x.

By far the most common error using scanf is leaving out the & before a variable as in:

    scanf("%d", n);
instead of
This error is not generally detected at compile time.

Input Conversion

The scanf statement reads characters from the standard input (the keyboard), interprets them according to the field specification, and stores the results in the address specified in the address list.

For example, in the scanf statement:

the "%d" in the field specification indicates the input should be interpreted as a decimal integer and the "&x" means that the integer read is stored at the address of x. Other field specifications include:

With the exception of the character code (c), the scanf function skips leading whitespace. That means that the scanf function will ignore leading spaces, tabs or newlines entered at the keyboard. If the format code is character, then scanf will read exactly one character (including whitespace characters).

Literal characters can appear in the scanf format string; they must match the same characters in the input. So we could read dates of the form mm/dd/yy with the following scanf statement:

The Program

 * Your name
 * CS 1511 Section ?
 * Today's date
 * Lab #4

#include <stdio.h>

void main()
  /* program to accept the name, age, sex and salary of 2 people from a user 
and then print out the details of the person the user specifies*/

  char f1, f2;
  char m1, m2;
  char l1, l2;
  int age1, age2;
  int id1, id2;
  char sex1, sex2;
  float sal1, sal2;
  int p;

  /* Input details of first person from user*/
  printf("Enter the first, middle and last initials of the name of first person:");
  printf("Enter the age and id of first person:");

  /* ERROR 1*/

  scanf("%d %d",age1,&id1);
  printf("Enter the sex of first person (m/f) :");
  printf("Enter the salary of first person    :");
  /* Input details of second person from user*/
  printf("\n\nEnter the first, middle and last initials of the name of second person:");
  printf("Enter the age and id of second person:");
  scanf("%d %d",&age2,&id2);
  printf("Enter the sex of second person (m/f) :");

  /* ERROR 2 */

  printf("Enter the salary of second person    :");

  /* ERROR 3 */

  /* display the details of one of the persons */
  printf("\n\nInput person number whose details you need (Enter 1 or 2):");
        printf("\nPerson %d's details\n",p);
        printf("Name  :%c.%c.%c\n",f1,m1,l1);
        printf("Age   :%d\n",age1);
        printf("Id    :%d\n",id1);
        printf("Sex   :%c\n",sex1);
        printf("\nPerson %d's details\n",p);
        printf("Name  :%c.%c.%c\n",f2,m2,l2);
        printf("Age   :%d\n",age2);
        printf("Id    :%d\n",id2);
        printf("Sex   :%c\n",sex2);

Corrections of Run-Time Errors

When you run the program initially, you will notice that when you are entering the information you come across a general protection exception. This is because of two errors that exist in the program. The scanf routine is used inappropriately in this program.

You can correct the program as follows:

Experimentation with Scanf

Backing on an Input Line

Assuming you have typed some data on an input line and you think that the input you have typed is inappropriate, if you have not pressed return after entering the data, you can always backup on the input line and delete whatever data you have typed. Try this out while running the program. Make a mistake on some line and then backup using the BackSpace key and correct your input before hitting Enter/Return.

Inappropriate Input

After you have made the above changes, try to see what happens if you enter an non-integer value when the input required is of the integer type. For example, try typing A when a number is required. Several things can result (depending on the compiler/computer you are using): (1) the program may continue on skipping the rest of the input in the scanf command and storing garbage values; (2) the program may "lock up" -- stop responding; or (3) the program may report a run-time error and stop.

Not Enough Input

On the line asking for the age and id number of person 1 try typing a single number and pressing RETURN. The program will move the cursor to the start of the next line, but will stop there. Why? Because it is expecting you to type in the next number. Type in the second number and see what happens.

Too Much Input

Try the following. After type the initials of the first person, add a digit such as 1 on the same line. Now, when you are asked for the age and id of person 1 only type one number and hit RETURN. Perhaps surprisingly, the program continues, but did we enter two numbers? The answer is yes, the 1 we typed on the previous line was not read when the initials were being scanned, so when the computer asked for the age and id the 1 was still left to be read and it was used as the age of person 1. So only one more number has to be read.

To deal with this situation we can use the command fflush(stdin). This command tells the computer that before the next command is executed, any input already typed at the keyboard should be discarded (flushed), so that left over input from previous lines is ignored. Try adding this command before the scanf line reading in age1 and id1 and repeating the input pattern discussed above.

Some Practice with scanf Statements

Now that you have had some experience with scanf statements, get some practice framing scanf statements for the following:

What To Turn In

Turn in hard copies of the source code after you have made all the corrections. You will also need to turn in the output of the program after you have made the first two corrections, the correct output (after the final runtime error has been corrected) and finally a printout of the test run when you input inappropriate data. Turn in the two examples of scanf statements you created while practicing. Be sure to include a cover sheet specifying your name, course number (CS1511), section number and lab number when you submit the lab assignment.