string function

Hello everybody.
I have a quick question.

I have this function that reads a line of string.
And it reads it pretty well. I'm really curious how does it work.

1
2
3
4
5
6
7
8
string readline()	
{
	cin.clear();
	cin.ignore(cin.rdbuf()->in_avail());
	string line;
	getline(cin, line);
	return line;
}


I don't really understand what's the role of cin.clear() and cin.ignore(cin.rdbuf()->in_avail()).
Last edited on
cin.clear() clears all error flags that may be set on cin (that may be caused by a previous input operation failing, or something the like). That shouldn't be there, if an error did occur somewhere it should be handled there, not just randomly discarded in the next input operation.

cin.ignore(cin.rdbuf()->in_avail()) discards all characters that may be left over from previous input operations.

See also: http://www.cplusplus.com/reference/iostream/istream/
Topic archived. No new replies allowed.