haelmic
haelmic

Reputation: 610

Is it possible to manually set istream fail bit in C++11

I've made this class:

class object {
  // data...
 public:
  friend std::istream& operator>>(std::istream& in, object& o) {
    char c, d;
    in >> c >> d;
    if (c == d) {
      /*set the fail bit some how*/
      in.putback(d);
      in.putback(c);
    } else
      o.set_data(c, d);
    return in;
  }
};

I was looking at the documentation (not well) but couldn't find a proper way to set the fail bit. The reason I care is I'd like to be able to while(std::cin>>obj)/*do stuff*/; like one can do with an int. But if I currently do this there would be an infinite loop any time there was an error. -_- Is setting the fail bit possible or am I going to have to work with this problem a different way?

Upvotes: 8

Views: 3064

Answers (2)

songyuanyao
songyuanyao

Reputation: 172924

You can use setstate. Note you should put it after the invoke of putback, otherwise the chars won't be putbacked successfully because the stream has been in an error condition. i.e.

if (c==d) {

    in.putback(d);
    in.putback(c);

    /*set the fail bit some how*/
    in.setstate(std::ios_base::failbit);
}

Upvotes: 6

user1593881
user1593881

Reputation:

You can set the failbit of an input stream using the basic_ios::setstate function:

in.setstate(std::ios_base::failbit);

Upvotes: 11

Related Questions