Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would we call cin.clear() and cin.ignore() after reading input?

Google Code University's C++ tutorial used to have this code:

// Description: Illustrate the use of cin to get input // and how to recover from errors.  #include <iostream> using namespace std;  int main() {   int input_var = 0;   // Enter the do while loop and stay there until either   // a non-numeric is entered, or -1 is entered.  Note that   // cin will accept any integer, 4, 40, 400, etc.   do {     cout << "Enter a number (-1 = quit): ";     // The following line accepts input from the keyboard into     // variable input_var.     // cin returns false if an input operation fails, that is, if     // something other than an int (the type of input_var) is entered.     if (!(cin >> input_var)) {       cout << "Please enter numbers only." << endl;       cin.clear();       cin.ignore(10000,'\n');     }     if (input_var != -1) {       cout << "You entered " << input_var << endl;     }   }   while (input_var != -1);   cout << "All done." << endl;    return 0; } 

What is the significance of cin.clear() and cin.ignore()? Why are the 10000 and \n parameters necessary?

like image 984
JacKeown Avatar asked Feb 27 '11 05:02

JacKeown


People also ask

How does ignore () Work C++?

Ignore function is used to skip(discard/throw away) characters in the input stream. Ignore file is associated with the file istream. Consider the function below ex: cin. ignore(120,'/n'); the particular function skips the next 120 input character or to skip the characters until a newline character is read.

What is CIN ignore in Java?

In java equivalent of cin.ignore() is InputStream.skip() . You can refer to Java Docs. Follow this answer to receive notifications.

How do I completely clear my Cin?

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.

How do I ignore spaces in Cin?

You can use cin but the cin object will skip any leading white space (spaces, tabs, line breaks), then start reading when it comes to the first non-whitespace character and then stop reading when it comes to the next white space. In other words, it only reads in one word at a time.


Video Answer


1 Answers

The cin.clear() clears the error flag on cin (so that future I/O operations will work correctly), and then cin.ignore(10000, '\n') skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure). It will only skip up to 10000 characters, so the code is assuming the user will not put in a very long, invalid line.

like image 179
Jeremiah Willcock Avatar answered Sep 22 '22 10:09

Jeremiah Willcock