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;
printf(“Enter a number\n”);
printf(“Enter a character\n”);
printf(“The value of num is %d and ch is %c”,num,ch);

The output of the program is shown below

Enter a number
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”);
printf(“Enter a character\n”);

Hope you know understood the importance of ‘ffush’ statement


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

kavi said...

I would highly appreciate if you guide me through this. Thanks for the article…
Nice One...
For Tamil News Visit.. |