According to C++ regulation, we can recover istream (ist) from fail state if not encountered serious problems using ist.clear() statement.
But there is a question, if ist encountered an exception while reading and lead fail bit being set, with clear() statement we can recover istream to normal state.
Here is the question, would we start from where it failed? Which would mean the same position in the stream would be read twice, which seems controversy to its normal behavior: the content of a file can be read only once if sequentially? Many thanks!
Following is the code snippet with revision while I'm reading Bjarne Stroustrup's Programming: Principles and Practice Using C++ (2nd Edition)
std::cin.clear() to reset the fail state, then follow with std::cin.ignore(1000, '\n') to clear the stream, keeping in mind the figure of 1000 is sufficiently large generally but the 'real' approach to that number uses <limit> which is easy to chase up by a quick google .
@kemort
Thank you sir, but does cin.ignore() really matter with the code above?
@JLBorges
Thank you so much, FYI, the code above especially the case where ist failed does not try to extract the stream twice but clears the state and advances to process the next, which is expected to be a terminator?
Am I correct?
Also, the code snippet above is expected to do something like this:
1 2 3 4 5 *
> does not try to extract the stream twice but clears the state and advances to process the next, > which is expected to be a terminator? Am I correct?
Yes.
If the last digit of an integer in the stream is followed by the terminartor (say, a '*'):
The extraction the first int would stop at the terminator; the terminator will remain in the input stream.
The attempt to extract another int would fail because it encounters the terminator first-up; it will put the stream into a failed state without extracting the terminator.
Clear the failed state and extract a char; the terminator would be extracted.
Thank you sir, but does cin.ignore() really matter with the code above?
Given what Stroustrup is demonstrating now that I have read his explanation and less obscure sample you are correct in questioning the use of ignore() as I suggested. In fact using it would be very unhelpful if data was still to be read after the terminator.