// Time.cpp #include "Time.h" #include using std::istream; istream & operator>>( istream & in, Time & t ) { // read hours after skipping whitespace int h = 99; in >> h; // Note: we don't read directly into t.hours_ so we can leave // it unchanged in case of an error. if ( in.fail() || in.bad() ) return in; // no int in stream if ( in.eof() || h < 0 || h > 23 ) { // if eof, an int but nothing else in.setstate(in.failbit); // add fail state to stream return in; } // make sure next char is colon char next_char = in.peek(); // Note: we don't read the char until we're sure it's a colon. if ( !in ) return in; // Note: bad or good were the only possibilities. if ( next_char != ':' ) { in.setstate(in.failbit); return in; } in.get(); // read colon // make sure next char is not whitespace next_char = in.peek(); if ( !in ) return in; if ( next_char == ' ' || next_char == '\t' || next_char == '\n' ) { in.setstate(in.failbit); return in; } // read minutes int m = 99; in >> m; if ( in.fail() || in.bad() ) return in; // Note: eof is possible if the minutes were at the very // end of the file. This shouldn't make the time invalid // but we leave the stream in the eof state. if ( m < 0 || m > 59 ) { in.setstate(in.failbit); return in; } // all good (except possibly for the number of digits in // the hours and minutes) t.set_hours(h); t.set_minutes(m); return in; }