Friday, November 1, 2013

Checking successfully scanned input items.


When you entered data using keyboard then always remember that the data items must corresponds to the arguments in scanf() function in number, type and in order. Violation of this rule may cause unexpected results.
You can use the scanf() function to return the number of input fields successfully scanned, converted and stored.
Look at the following program to make this fact clearer.
Program 13:

#include <stdio.h>
#include <conio.h>
void main()
{
          int age,nof;/* Number of fields. */
char gender;
clrscr();
printf(“Enter gender and age:”);
nof=scanf(“%c%d”,&gender,&age);
if(nof==2)
{
          printf(“\nCorrect input!”);
printf(“\nGender=%c\nAge=%d”,gender,age);
printf(“\nNumber of input field scanned=%d”,nof);
}
else
{
printf(“\nWrong input!”);
         printf(“\nGender=%c\nAge=%d”,gender,age);
printf(“\nNumber of input field scanned=%d”,nof);
}
getch();
}
Run the program. Input the value of sex=12 and age=25. Observe the output.
Output:
#----------------------------------------------------------------#
Enter gender and age:12 25
Correct input!
Gender=1
Age=2
Number of input field scanned=2
#----------------------------------------------------------------#
Oops! You might be surprised that our input data is valid. How? When you enter 12 for gender then compiler assigns 1 to the variable gender (remember that in character variable we can store only one character either it is alphabet, number or special character). The unread data from the inputted number 12 i.e. 2 in this case is assigned to the variable age. So the next data input that is 25 remains unread. If our program contains another scanf(), then this unread data is used by the compile for the next scan data. So, be cautious about such errors.
Now, run the program with the following
Enter gender and age:m m
Wrong input!
Gender=m
Age=-28727
Number of input field scanned=1


This time the compiler reports invalidity of input. Observe that, the value of variable is a garbage value and it may be different when you run this program.

No comments:

Post a Comment