Clear cin in C ++

Possible duplicate:
Why is this cin reading jammed?

I overloaded the istream operator ( istream &operator>>... ) and it takes a point in the format:

 (<x-coordinate>,<y-coordinate>) 

I want to check this several (10) times, and therefore wrote:

 for (int i = 0; i < 10; i++) { cin >> a; if (!cin.fail()) { cout << a << endl; } else { cout << "Invalid input!" << endl; cin.clear(); } } 

EDIT:

Now I have the following code:

 for (int i = 0; i < 10; i++) { cin >> a; if (!cin.fail()) { cout << a << endl; } else { cout << "Invalid input!" << endl; cin.clear(); while (!cin.eof()) { cin.ignore(); } cin.ignore(); } } 

Rejection was proposed by Cthulhu. However, the problem is that cin still outputs "Invalid input!" after executing the code above:

 (3,3) <-- input (3,3) <-- output Invalid output! <-- second output 

Is there a way that I can clear what is in cin?

+4
source share
1 answer

cin.clear() does not free the buffer, it resets the error flags in the stream. Then you need to call cin.ignore

 istream& ignore ( streamsize n = 1, int delim = EOF ); 

Extracts characters from the input sequence and discards them.

The extraction ends when n characters have been retrieved and discarded, or when the character of the character is found, whichever comes first. In the latter case, the separator character itself is also highlighted.


 cin.clear(); cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 

Numerical restrictions

+2
source

Source: https://habr.com/ru/post/1442558/


All Articles