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

The Google Code University C ++ tutorial used 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 meaning of cin.clear() and cin.ignore() ? Why are parameters 10000 and \n needed?

+62
c ++ input iostream
Feb 27 '11 at 5:17
source share
3 answers

cin.clear() clears the cin error flag (so that future I / O will work correctly), and then cin.ignore(10000, '\n') moves to the next new line (to ignore anything else in the same line, -number so that it does not cause another analysis failure). It will only skip up to 10,000 characters, so the code assumes that the user will not enter a very long invalid string.

+75
Feb 27
source share

You enter

 if (!(cin >> input_var)) 

if an error occurs while entering data from cin. If an error occurs, the error flag is set, and future attempts to get input will fail. That's why you need

 cin.clear(); 

to get rid of the error flag. In addition, an input that has failed will sit in what I assume is a kind of buffer. When you try to get input again, it will read the same input in the buffer and it will work again. That's why you need

 cin.ignore(10000,'\n'); 

It takes out 10,000 characters from the buffer, but stops if it encounters a new line (\ n). 10000 is just a total value.

+29
Feb 27 '11 at 5:44
source share

use cin.ignore(1000,'\n') to clear all the characters of the previous cin.get() in the buffer and it will stop when it first encounters '\ n' or 1000 chars .

+1
Dec 20 '15 at 10:19
source share



All Articles