#include "time.h" #include #include #include #include using namespace std; __BadTimeException::__BadTimeException(const string& s) : time(s) { } // predicate that determines if a character is a digit struct is_digit { typedef char argument_type; // needed so that we can pass it to not1 bool operator()(char c) const { return isdigit(c); } }; // are all the digits in the range digits? bool all_digits(string::iterator begin, string::iterator end) { return find_if(begin, end, not1(is_digit())) == end; } void Time::parse_time(const std::string& time) { // find the colon size_t colon_pos = time.find(':'); if (colon_pos == string::npos) // colon not found { throw Time::BadTimeException(time); } // split it up into two parts string hours_str = time.substr(0, colon_pos); string minutes_str = time.substr(colon_pos+ 1); if (hours_str.size() == 0 || minutes_str.size() == 0) { throw Time::BadTimeException(time); } // check that they consist entirely of digits (with optional leading minus sign) if (!all_digits(hours_str.begin() + (hours_str[0] == '-'), hours_str.end()) || !all_digits(minutes_str.begin() + (minutes_str[0] == '-'), minutes_str.end())) { throw Time::BadTimeException(time); } stringstream hours_ss(hours_str), minutes_ss(minutes_str); int h, m; hours_ss >> h; minutes_ss >> m; set_time(h, m); } Time::Time(int m) { set_total_minutes(m); } Time::Time(int h, int m) { set_time(h, m); } Time::Time(const std::string& time) : minutes(0) { parse_time(time); } pair Time::get_time() const { return make_pair(minutes / MINUTES_IN_HOUR, minutes % MINUTES_IN_HOUR); } void Time::set_time(int h, int m) { set_total_minutes(h * MINUTES_IN_HOUR + m); } int Time::get_total_minutes() const { return minutes; } void Time::set_total_minutes(int m) { minutes = m % MINUTES_IN_DAY; if (minutes < 0) { minutes += MINUTES_IN_DAY; } } Time Time::operator+(const Time& t) const { Time ret = *this; ret += t; return ret; } Time Time::operator-(const Time& t) const { Time ret = *this; ret -= t; return ret; } Time& Time::operator+=(const Time& t) { set_total_minutes(minutes + t.get_total_minutes()); } Time& Time::operator-=(const Time& t) { set_total_minutes(minutes - t.get_total_minutes()); } std::string Time::to_string() const { std::stringstream ss; int h = minutes / MINUTES_IN_HOUR; int m = minutes % MINUTES_IN_HOUR; ss << setw(2) << setfill('0') << h << ":" << setw(2) << m; std::string ret; ss >> ret; return ret; } bool Time::operator==(const Time& other) const { return minutes == other.minutes; } std::ostream& operator<<(std::ostream& out, const Time& t) { return cout << t.to_string(); } std::istream& operator>>(std::istream& in, Time& t) { std::string temp; in >> temp; t = Time(temp); }