Clearing The Input Buffer In C/C++

3.2

What is buffer?
Temporary storage area is called buffer. All standard input and output devices contain input and output buffer. In standard C/C++, streams are buffered, for example in case of standard input,when we press the key on keyboard,it isn’t send to your program, rather it is buffered by operating system till the time is allotted to the program.


How does it effect Programming?

On various occasions you may need to clear the unwanted buffer so as to get the next input in the desired container and not in the buffer of previous variable. For example, in case of C after encountering “scanf()” , if we need to input a character array or character ,and in case of C++, after encountering“cin” statement, we require to input a character array or a string , we require to clear the input buffer or else the desired input is occupied by buffer of previous variable, not by the desired container.On pressing “Enter” (carriage return) on output screen after the first input , as the buffer of previous variable was the space for new container(as we did’nt clear it) , the program skips the following input of container.

In case of C Programming

// C Code to explain why not clearing the input buffer
// causes undesired outputs
#include<stdio.h>
int main()
{
    char str[80], ch;
    
    // Scan input from user -GeeksforGeeks for example
    scanf("%s", str);
    
    // Scan character from user- 'a' for example
    ch = getchar();
    
    // Printing character array, prints “GeeksforGeeks”)
    printf("%s\n", str);
    
    // This does not print character 'a'
    printf("%c", ch);
    
    return 0;
}

Input:

GeeksforGeeks
a

Output:

GeeksforGeeks

In case of C++

// C++ Code to explain why not clearing the 
// input buffer causes undesired outputs
#include<iostream>
#include<vector>
using namespace std;
int main()
{
    int a;
    char ch[80];
    
    // Enter input from user - 4 for example
    cin >> a;
    
    // Get input from user - "GeeksforGeeks" for example
    cin.getline(ch,80);
    
    // Prints 4
    cout << a << endl;
    
    // Printing string : This does not print string
    cout << ch << endl;

    return 0;
}

Input:

4
GeeksforGeeks

Output:

4

In both the above codes, the output is not printed as desired. Reason to this is an occupied Buffer. The “\n” character goes remains there in buffer and read as next input.

 
How can it be resolved?

In case of C :

  1. Using “ while ((getchar()) != ‘\n’); ” : Typing “while ((getchar()) != ‘\n’);” reads the buffer characters till the end and discards them(including newline) and using it after the “scanf()” statement clears the input buffer and allows the input in the desired container.
    // C Code to explain why adding "while ( (getchar()) != '\n');"
    // after "scanf()" statement flushes the input buffer
    #include<stdio.h>
    int main()
    {
        char str[80], ch;
        
        // scan input from user - GeeksforGeeks for example
        scanf("%s", str);
        
        // flushes the standard input (clears the input buffer)
        while ((getchar()) != '\n');
        
        // scan character from user - 'a' for example
        ch = getchar();
        
        // Printing character array, prints “GeeksforGeeks”)
        printf("%s\n", str);
        
        // Printing character a: It will print 'a' this time
        printf("%c", ch);
    
        return 0;
    }
    

    Input:

    GeeksforGeeks
    a
    

    Output:

    GeeksforGeeks
    a
    
  1. Using “ fflush(stdin) ” : Typing “fflush(stdin)” after “scanf()” statement also clears the input buffer but use of it is avoided and is termed to be “undefined” for input stream as per the C++11 standards.

In case of C++ :

  1. Using “ cin.ignore(numeric_limits::max(),’\n’); ” :- Typing “cin.ignore(numeric_limits::max(),’\n’);” after the “cin” statement discards everything in the input stream including the newline.
    // C++ Code to explain how "cin.ignore(numeric_limits
    // <streamsize>::max(),'\n');" discards the input buffer
    #include<iostream>
    #include<ios>     // for <streamsize>
    #include<limits>  // for numeric_limits
    using namespace std;
    int main()
    {
        int a;
        char str[80];
        
        // Enter input from user - 4 for example
        cin >> a;
        
        // discards the input buffer
        cin.ignore(numeric_limits<streamsize>::max(),'\n');
        
        // Get input from user - GeeksforGeeks for example
        cin.getline(str, 80);
        
        // Prints 4
        cout << a << endl;
        
        // Printing string : This will print string now
        cout << str << endl;
    
        return 0;
    }
    

    Input:

    4
    GeeksforGeeks
    

    Output:

    4
    GeeksforGeeks
    
  1. Using “ cin.sync() ” : Typing “cin.sync()” after the “cin” statement discards all that is left in buffer. Though “cin.sync()” does not work in all implementations (According to C++11 and above standards).
    // C++ Code to explain how " cin.sync();" 
    // discards the input buffer
    #include<iostream>
    #include<ios>     
    #include<limits>  
    using namespace std;
    int main()
    {
        int a;
        char str[80];
        
        // Enter input from user - 4 for example
        cin >> a;
        
        // Discards the input buffer
        cin.sync();
        
        // Get input from user - GeeksforGeeks for example
        cin.getline(str, 80);
        
        // Prints 4
        cout << a << endl;
        
        // Printing string - this will print string now
        cout << str << endl;
    
        return 0;
    }
    

    Input:

    4
    GeeksforGeeks
    

    Output:

    4
    GeeksforGeeks
    
  1. Using “ cin >> ws ” : Typing “cin>>ws” after “cin” statement tells the compiler to ignore buffer and also to discard all the whitespaces before the actual content of string or character array.
    // C++ Code to explain how "cin >> ws" discards 
    // the input buffer along with initial white spaces
    // of string
    #include<iostream>
    #include<vector> 
    using namespace std;
    int main()
    {
        int a;
        string s;
       
        // Enter input from user - 4 for example
        cin >> a;
        
        // Discards the input buffer and intial white spaces of string
        cin >> ws;
        
        // Get input from user - GeeksforGeeks for example
        getline(cin, s);
        
        // Prints 4 and GeeksforGeeks : will execute print a and s
        cout << a << endl;
        cout << s << endl;
    
        return 0;
    }
    

    Input:

    4
    GeeksforGeeks
    

    Output:

    4
    GeeksforGeeks
    

This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



3.2 Average Difficulty : 3.2/5.0
Based on 45 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.