Clearing The Input Buffer In C/C++
What is a buffer?
A temporary storage area is called buffer. All standard input and output devices contain an input and output buffer. In standard C/C++, streams are buffered, for example in the case of standard input, when we press the key on keyboard, it isn’t sent to your program, rather it is buffered by operating system till the time is allotted to that 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 :
- 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>intmain(){charstr[80], ch;// scan input from user -// GeeksforGeeks for examplescanf("%s", str);// flushes the standard input// (clears the input buffer)while((getchar()) !='\n');// scan character from user -// 'a' for examplech =getchar();// Printing character array,// prints “GeeksforGeeks”)printf("%s\n", str);// Printing character a: It// will print 'a' this timeprintf("%c", ch);return0;}chevron_rightfilter_noneInput:
GeeksforGeeks a
Output:
GeeksforGeeks a
- 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++ :
- 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>// for <streamsize>#include<ios>// for numeric_limits#include<limits>usingnamespacestd;intmain(){inta;charstr[80];// Enter input from user// - 4 for examplecin >> a;// discards the input buffercin.ignore(numeric_limits<streamsize>::max(),'\n');// Get input from user -// GeeksforGeeks for examplecin.getline(str, 80);// Prints 4cout << a << endl;// Printing string : This// will print string nowcout << str << endl;return0;}chevron_rightfilter_noneInput:
4 GeeksforGeeks
Output:
4 GeeksforGeeks
- 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>usingnamespacestd;intmain(){inta;charstr[80];// Enter input from user// - 4 for examplecin >> a;// Discards the input buffercin.sync();// Get input from user -// GeeksforGeeks for examplecin.getline(str, 80);// Prints 4cout << a << endl;// Printing string - this// will print string nowcout << str << endl;return0;}chevron_rightfilter_noneInput:
4 GeeksforGeeks
Output:
4
- 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>usingnamespacestd;intmain(){inta;string s;// Enter input from user -// 4 for examplecin >> a;// Discards the input buffer and// intial white spaces of stringcin >> ws;// Get input from user -// GeeksforGeeks for examplegetline(cin, s);// Prints 4 and GeeksforGeeks :// will execute print a and scout << a << endl;cout << s << endl;return0;}chevron_rightfilter_noneInput:
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.
Recommended Posts:
- Check if given Preorder, Inorder and Postorder traversals are of same tree | Set 2
- getdate() and setdate() function in C with Examples
- Intel Graphics Software Engineer Interview Experience
- OpenMP | Introduction with Installation Guide
- Equation of straight line passing through a given point which bisects it into two equal line segments
- Maximum absolute difference in an array
- Count the pairs of vowels in the given string
- X-Macros in C
- Why overriding both the global new operator and the class-specific operator is not ambiguous?
- Print path from root to all nodes in a Complete Binary Tree
- Count the number of 1's and 0's in a binary array using STL in C++ ?
- Find elements of an Array which are Odd and Even using STL in C++
- Find elements of an array which are divisible by N using STL in C++
- All reverse permutations of an array using STL in C++
- Generics in C++
Improved By : tornado711



