I am overloading the input stream operator for use with a Time class and would like to manually set the failbit of the input stream if the input doesn't match my expected time format (hh:mm). Can this be done? How?
Thanks!
Join Stack Overflow to learn, share knowledge, and build your career.
I am overloading the input stream operator for use with a Time class and would like to manually set the failbit of the input stream if the input doesn't match my expected time format (hh:mm). Can this be done? How?
Thanks!
Yes, you can set it with ios::setstate
, like so:
#include <iostream>
#include <ios>
int main()
{
std::cout << "Hi\n";
std::cout.setstate(std::ios::failbit);
std::cout << "Fail!\n";
}
The second output will not be produced because cout
is in the failed state.
(An exception seems cleaner to me, but YMMV)
failbit
is a very valid approach to reporting streaming errors as client code can use the same if (in >> val) { /* success */ }
idiom that they can use for basic types.
– CB Bailey
Oct 28 '09 at 22:57
operator >>(in, custom_type& c)
: if ((in >> member1) && (in >> member2)) { c = custom_type{move(member1), move(member2)}; } else { in.setstate(std::ios::failbit); } return in;
. When written like this, you could embed custom_type
in another object and read with a similar implementation (it stacks up nicely). The reason I like it, is because an 'if' is easier to write than a 'try/catch' block (for the client code) - it imposes less restrictions.
– utnapistim
Jun 11 '14 at 17:42