Handling invalid input in input stream operator >>

Viewed 264

What is the recommended (standard) way of handling invalid input in extraction operator:

std::istream& operator>>(std::istream& is, SomeType& val) {
    // ...
    return is;
}

Should it set std::ios_base::failbit and return immediately? Is it okay to leave the val object in undefined state, with possibly some of it's variables already changed?

2 Answers

According to FormattedInputFunction documentation the recommended layout:

std::istream& operator>>(std::istream& is, SomeType& val) {
    std::istream::sentry s(is);
    if (s) {
         // do parse
         if (parsing_failed) {
             // optionally, to make it work like built-in operators:
             // val = {};
             is.setstate(std::ios_base::failbit);
         }
    }
    return is;
}

I would follow the convention of the standard library - that is, set failbit, leave the stream pointing to the same place you started with and set your input to some default value - the standard library sets inputs to 0 on error, so do whatever the logical equivalent of that for your type is, probably val = SomeType{};.

Related