ss_blog_claim=726e70d7c87c20ae33aa7a61f06eb8aa

Saturday, November 15, 2008

The usage of ‘fflush’ statement in C programming

The keyboard has an input buffer in it and every time you read data from the keyboard the value stored in the input buffer is read. For every key press there will be a value loaded into the input buffer which means that the ‘Enter’ key, ‘Tab’ key also has a value being stored in the buffer when pressed.


We know that the ‘Enter’ key and the ‘Tab’ key acts as a delimiter while accepting data. Consider the below C Program

void main()
{
int num;
char ch;
clrscr();
printf(“Enter a number\n”);
scanf(“%d”,&num);
printf(“Enter a character\n”);
scanf(“%c”,&ch);
printf(“The value of num is %d and ch is %c”,num,ch);
getch();
}

The output of the program is shown below

Enter a number
12
Enter a character
The value of num is 12 and ch is

Wonder why this happens? Well let us look at the problem. When you type the number 12 and press ‘Enter’ key, the value corresponding to key press ‘1’ and ‘2’ is read from the input buffer and gets assigned to the variable ‘num’ once you press the ‘Enter’ key(delimiter). Now the value of the ‘Enter’ key is stored in the input buffer. So when you want to read a character, the value of the ‘Enter’ key which is stored in the input buffer is assigned to the character variable ‘ch’. This results in giving a wrong output. This is where the ‘fflush’ command comes into picture. The ‘fflush’ clears the specified buffer, so after getting the integer value we need to clear the input buffer (which stores the ‘Enter’ key value) before getting the character value. So the C program is changed as shown below.

printf(“Enter a number\n”);
scanf(“%d”,&num);
fflush(stdin);
printf(“Enter a character\n”);
scanf(“%c”,&ch);

Hope you know understood the importance of ‘ffush’ statement

5 comments:

Kind of Technology said...
This comment has been removed by a blog administrator.
Unknown said...

thanks a lot

Raquib said...

when we press the once enter key then 12 is stored in num variable , and the value of enter key stored in input buffer , but i could not understand that how ch variable gets a blank space

Julia Loi said...

Usually I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job Man, Keep it up.mobile phone repair in Novi
iphone repair in Novi
cell phone repair in Novi
phone repair in Novi
tablet repair in Novi
ipad repair in Novi
mobile phone repair Novi
iphone repair Novi
cell phone repair Novi
phone repair Novi

Unknown said...

I Know a very wonderful car in usa . this car price is very nice. so you can buy it .
read more..
https://www.toyota.com/4runner/