Pages

Tuesday, September 29, 2009

Using Char along with Integer and Float

If we want to write a program in which we need to enter a character values(%c) along with integer (%d) or float (%f) value, we have to be a bit careful. C generally doesn't allow %c to be entered with %d. Consider the following program.

Example 1 : The error program

void main()
{
char grade;
int marks;
printf("\nEnter Grade : ");
scanf("%c",&grade);
printf("\nEnter Marks : ");
scanf("%d",&marks);
}

When you compile the above program, you will notice that the program terminates unexpectdly when the grade is entered without giving you the time to enter marks. The same problem arises when you try to use %c with %f. The solution of the problem is a function named "fflush()". Just put this function between
scanf("%c",&grade);
and
printf("\nEnter Marks : ");

The code should now look like this

Example 1 : The correct code rewrittrn using fflush(stdin)
void main()
{
char grade;
int marks;
printf("\nEnter Grade : ");
scanf("%c",&grade);
fflush(stdin);// stdin stands for Standard Input
printf("\nEnter Marks : ");
scanf("%d",&marks);
}
Run the program again and you will that the program is working perfectly and will allow you to enter the value of marks.

Whenever we want to enter a char after integer/float or vice versa, we'll to use fflush(stdin). It may be needed more than once in a program if there are multiple values to be entered of different types.

0 comments:

Post a Comment