Understanding cin.clear() and cin.ignore() in C++



When we attempt to work with user input in C++, unwanted behavior may be caused by errors or leftover characters in the input buffer. So, in that case cin.clear() and cin.ignore() are functions that can help in dealing with this kind of problem.

cin.clear()

The cin.clear() resets the error flags on the cin stream and is used when an input operation fails (e.g., entering a non-numeric value for an integer variable).

Without clearing the error flags, further input operations will not work.

Example

In this example, we take input from the user and check if the input is invalid. If so, it clears the error state to allow further input processing.

#include <iostream>
using namespace std;
int main() {
   int num;
   cin >> num;
   if (cin.fail()) { // Check if input failed
      cout << "Invalid input. Clearing error flags..." << endl;
      cin.clear(); // Reset error flags
   }
   return 0;
}

Output

Following is the output to the above program ?

Invalid input. Clearing error flags...

cin.ignore()

The cin.ignore() skips characters in the input buffer and used to remove unwanted characters left in the buffer after an input operation.

We can specify the number of characters to skip and the delimiter to stop skipping.

Example

In this example, we take an input from the user and clear the remaining characters (up to 1000 or until a newline) from the input buffer and then we conclude that the buffer is ready for the next input.

#include <iostream>
using namespace std;
int main() {
   int num;
   cin >> num;
   cin.ignore(1000, '\n'); // Skip up to 1000 characters or until a newline is encountered
   cout << "Buffer cleared. Ready for next input." << endl;
   return 0;
}

Output

Following is the output to the above program ?

Buffer cleared. Ready for next input.

Using both cin.clear() and cin.ignore()

Here, we are using both functions like:

cin.clear() that ensures the input stream is ready for new operations

cin.ignore() that removes leftover characters that could interfere with subsequent inputs.

Example

In this example, we take an user input to validate it. If the input is invalid, it resets error flags, clears the input buffer, and ensures the program can continue processing input successfully.

#include <iostream>
using namespace std;
int main() {
   int num;
   cin >> num;
   if (cin.fail()) {
      cout << "Invalid input. Clearing error flags and buffer..." << endl;
      cin.clear(); // Reset error flags
      cin.ignore(1000, '\n'); // Clear buffer
   }
   cout << "Input processed successfully." << endl;
   return 0;
}

Output

Following is the output to the above program ?

Invalid input. Clearing error flags and buffer...
Input processed successfully.
Revathi Satya Kondra
Revathi Satya Kondra

Technical Content Writer, Tutorialspoint

Updated on: 2025-04-11T17:33:40+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements