How do I clear the cin buffer in C++?

C++Server Side ProgrammingProgramming

In this section, we will see how to clear the cin buffer in C++. Before entering into that discussion, let us see what is the buffer in C++.

The buffer is a temporary storage area. All standard IO devices uses buffers to hold data while they are working. In C++ also the stream is basically the buffer. When we press some key, that does not send to the program. They are stored into buffers. It is buffered by the operating system till the time is allotted to the program.

Sometimes we need to clear the unwanted buffer, so when next input is taken, it stores into the desired container, but not in the buffer of previous variable. For example, after entering into the cin statement, we need to input a character array or string. So we need to clear the input buffer, otherwise it will occupy the buffer of previous variable. By pressing the “Enter” key after the first input, as the buffer of previous variable has space to hold new data, the program skips the following input of container.

Example

#include<iostream>
#include<vector>
using namespace std;
main() {
   int x;
   char str[80];
   cout << "Enter a number and a string:\n";
   cin >> x;
   cin.getline(str,80); //take a string
   cout << "You have entered:\n";
   cout << x << endl;
   cout << str << endl;
}

Output

Enter a number and a string:
8
You have entered:
8

There are two cin statements for integer and string, but the only number is taken. When we press enter key, it skips the getLine() function without taking any input. Sometimes it can take input but inside the buffer of integer variable, so we cannot see the string as output.

Now to resolve this issue, we will use the cin.ignore() function. This function is used to ignore inputs upto given range. If we write the statement like this

cin.ignore(numeric_limits::max(), ‘\n’)

Then it ignores input including the new line character also.

Example

#include<iostream>
#include<ios> //used to get stream size
#include<limits> //used to get numeric limits
using namespace std;
main() {
   int x;
   char str[80];
   cout << "Enter a number and a string:\n";
   cin >> x;
   cin.ignore(numeric_limits<streamsize>::max(), '\n'); //clear buffer before taking new line
   cin.getline(str,80); //take a string
   cout << "You have entered:\n";
   cout << x << endl;
   cout << str << endl;
}

Output

Enter a number and a string:
4
Hello World
You have entered:
4
Hello World
raja
Updated on 30-Jul-2019 22:30:25

Advertisements