What is the use of cin.ignore() in C++?


The cin.ignore() function is used which is used to ignore or clear one or more characters from the input buffer.

To get the idea about ignore() is working, we have to see one problem, and its solution is found using the ignore() function. The problem is like below.

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 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

Updated on: 02-Sep-2023

53K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements