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

Question

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

Answers 2
Added at 2016-12-28 04:12
Tags
Question

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?

Answers
nr: #1 dodano: 2016-12-28 04:12

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

in.setstate(std::ios_base::failbit);
nr: #2 dodano: 2016-12-28 04:12

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);
}
Source Show
◀ Wstecz