Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*** HPP ***/
- class TimeString {
- private:
- vector<string> str_vec;
- int _h = 0;
- int _m = 0;
- double _s = 0;
- double total_sec = 0;
- bool is_valid = false;
- string timestr;
- void TimeString::to_timestr(const string& str);
- void TimeString::to_timestr(double sec);
- void TimeString::build_string();
- public:
- // constructor
- TimeString();
- TimeString(const string& str);
- TimeString(double sec);
- // assignment
- TimeString operator=(const char* str);
- bool operator()(string str);
- // conversion
- operator const string();
- operator const double();
- operator const bool();
- // comparison
- bool operator<(double b);
- bool operator>(double b);
- // getters
- double h();
- double m();
- double s();
- };
- /*** CPP ***/
- void TimeString::to_timestr(const string& str) {
- if (str.empty()) return;
- if (timestr == str) return;
- timestr = str;
- is_valid = true;
- str_vec = split(str, ':');
- auto i = str_vec.end();
- // get seconds
- if (is_number(*--i)) {
- _s = ToI(*i);
- total_sec += _s;
- }
- else is_valid = false;
- if (is_valid == false || i == str_vec.begin()) return;
- // get minutes
- if (is_number(*--i)) {
- _m = ToI(*i);
- total_sec += _m * 60;
- }
- else is_valid = false;
- if (is_valid == false || i == str_vec.begin()) return;
- // get hours
- if (is_number(*--i)) {
- _h = ToI(*i);
- total_sec += _h * 3600;
- }
- else is_valid = false;
- return;
- }
- void TimeString::to_timestr(double sec) {
- is_valid = true;
- str_vec.resize(3, "0");
- total_sec = sec;
- _h = sec / 3600;
- _s = sec - _h * 3600;
- _m = _s / 60;
- _s = sec - _m * 60;
- }
- void TimeString::build_string() {
- if (!is_valid) return;
- if (timestr.size()) return;
- if (_h) timestr += ToS(_h) + ":";
- if (_m) timestr += ToS(_m) + ":";
- if (_s) timestr += ToS(_s) + ":";
- timestr.pop_back();
- }
- TimeString TimeString::operator=(const char * str) {
- to_timestr(str);
- return *this;
- }
- bool TimeString::operator()(string str) {
- to_timestr(str);
- return is_valid;
- }
- TimeString::operator const string() { build_string(); return timestr; }
- TimeString::operator const double() { return total_sec; }
- TimeString::operator const bool() { return is_valid; }
- bool TimeString::operator<(double b) { return total_sec < b; }
- bool TimeString::operator>(double b) { return total_sec > b; }
- TimeString::TimeString() {};
- TimeString::TimeString(const string& str) { to_timestr(str); }
- TimeString::TimeString(double sec) { to_timestr(sec); }
- double TimeString::h() { return _h; }
- double TimeString::m() { return _m; }
- double TimeString::s() { return _s; }
Advertisement
Add Comment
Please, Sign In to add comment