It is well known that cin is not typesafe (e.g. cin >> integer; and entering “fifty five” will cause it to flip out). I have seen many not-so-elegant ways to hand this, such as getlining a string and using sstream to convert it to a number, or looping with cin.fail() and clearing the stream and reentering it, etc. Is there any library or anyway to overload the extraction operator to make cin automatically typesafe?
Share
No, this will not cause it to “flip out;” it will cause the fail state of the stream to be set, just like with any other stream. This doesn’t mean that
std::cinis not type-safe.One option for handling errors reading from a stream would be to write a function template that performs the extraction, tests whether it succeeded, resets the error state on the stream if appropriate, and returns whether the extraction succeeded along with the result.