"A little progress everyday adds up to big results"

Monday 12 January 2015

C Programming : The (input) buffer problem

                      Usually in C programming, whatever we type gets stored in the keyboard buffer (temporary storage) and then the CPU takes input from the buffer. If a scanf is used to read input, this buffer is inspected first. If the input is available in the buffer itself, it is taken directly and the scanf statement terminates. Only if the buffer does not have the requested input, the user is prompted for input.
             
                    Whenever we input a number (int, float or double), we give the number and press enter to specify that our input is ready to be taken. Both (number and enter) are stored in the buffer.

                         After enter is pressed, the number gets stored in the (int, float or double) variable. But, where does the enter go? Yes, it remains in the buffer. Next time when a character or string is to be given as input, this enter will be taken directly from the keyboard buffer and we will not be prompted to input the character or string.

Example:
1.#include<stdio.h>
2.
3.int main()
4.{
5.          int num ;
6.          char ch ;
7.          printf ( "Number: " ) ;
8.          scanf ( "%d", &num ) ;
9.          printf ( "\nCharacter: " ) ;
10.        scanf ( "%c", &ch ) ;
11.        printf ( "%cBye", ch ) ;
12.        return 0 ;
13. }

Output:
Number: 2
Character:
Bye

Explanation:
2 is stored in num and '\n' ( enter ) is stored in ch.

Solution 1:
To get rid of this let us use getchar() before the second scanf(), that is at line number 10. getchar() takes the enter from the buffer. But, since we didn't assign it to any variable, it gets wasted (removed from the buffer).

Solution 2:
Instead of using getchar(), we may get the character twice, that is use scanf ( "%c %c", &ch, &ch ) ; instead of scanf ( "%c", &ch ) ; In this case, first enter is stored in ch and later, the input we give replaces it.

The best solution:Which one of the above do you think is the best solution? If you think it is solution 1, then you are wrong. If you think it is solution 2, then also you are wrong. Both of the above are only solutions, but not the best. The best and right solution is to clear the buffer using the inbuilt function.

              If you are a Turbo C programmer, use the following statement before line 10.
fflush (stdin);

                If you are a gcc programmer, use the following statement before line 10.
__fpurge (stdin); // It is double 'underscore' followed by fpurge
and include <stdio_ext.h>

Do not get caught in the buffer jail!

No comments:

Post a Comment