I came across this in my readings…
while(!(std::cin >> array[i]))
{
std::cin.clear();
while(std::cin.get()!= '\n')
continue;
std::cout << "enter a new input: ";
}
And, I don’t really understand how the error handling is working. std::cin.clear() is used but the code continues to get characters from the cin object in the next line and then uses a continue statement. What exactly does the clear do if it doesn’t clear the cin? Thank you.
what cin.clear() does is to clear the cin stream’s error flags.When it does this cin stream operations can continue.the next line extracts a character from the stream and returns it.
To understand what the loop does consider the following case :
Suppose the array is of type int and you enter:abc and then press enter.
cin identifies that the string input cannot go into the int array. and so it returns false and sets the error flags.when you perform cin.clear() it resets the error flags so that further operartions can continue(cin.get() can work).Now cin.get() extracts a from the stream. since it is not equal to ‘\n’ the loop continues(second loop) until it extracts ‘\n’ => meaning the wrong i/p you just entered is all washed away u can start afresh