How to use cin.ignore in C++ to clear input buffer
Hello, Coders! In this section, we will discuss and learn about the cin.ignore () function and its use in C++.
So, let’s cover the below topics briefly:
- Buffer
- cin.ignore() function
Use of Buffer in programming
- A buffer is a temporary storage device or some block of memory that is used to store the input and output values for the program. All the standard output and input devices contain an input and output buffer, respectively.
- When we give the input from the keyboard it doesn’t send the values to the program directly, instead, it stores them in the buffer and then is allotted to the program.
cin.ignore() in C++
- The
ignore()
function is used to ignore or discard the number of characters in the stream up to the given delimiter. - It is a member function of
std::basic_istream
and inherited from input stream classes. - It takes the number of characters and the delimiter character as arguments.
Syntax:
cin.ignore(n,d); //Where n = Number of Character // d = delimiter character //Example -> cin.ignore(100,'\n')
In some cases, we may need to delete the unwanted buffer, so that when a new value is taken next time, it stores the value in the appropriate buffer, not in the previous variable buffer.
Let’s understand the scenario by a program:
#include<iostream> #include<vector> using namespace std; int main() { int num; char name[20]; cout << "Enter your Roll Number and Name:\n"; cin >> num; cin.getline(name,20); // getline() take a string as input cout << "Your Details are:\n"; cout << num << endl; cout << name << endl; return 0; }
Output:
Enter your Roll Number and Name: 25 Your Details are: 25
In this example, we didn’t get the desired output from the program. We have taken two cin
input streams, one for the num
and the other from the string name
, but only the num
value is taken. It ignored the getline()
without taking any input value. In this case, the value goes to the num
variable buffer, as a result, we didn’t get the string value.
Here, we can use the cin.ignore()
to resolve the problem:
#include<iostream> #include<ios> //for stream size #include<limits> //for numeric limits using namespace std; int main() { int num; char name[20]; cout << "Enter your Roll Number and Name:\n"; cin >> num; //It will clear the buffer before taking the new input cin.ignore(numeric_limits<streamsize>::max(), '\n'); cin.getline(name,20); cout << "Your Details are:\n"; cout << num << endl; cout << name << endl; return 0; }
Output:
Enter your Roll Number and Name: 86 Sanam Your Details are: 86 Sanam
Note: numeric_limits<streamsize>::max()
is taken as an argument for the ignore()
function to force special cases and disable the number of characters.
I hope this C++ tutorial has helped you to give an idea about the cin.ignore() function, and its uses in C++.
Happy Codding !!
You can also read, Basic input/output in C++
Leave a Reply