Write a class timeStamp that represents a time of the day. It must have variables to store the number of seconds, minutes and hours passed (insert the values in SSMMHH format). It also must have a function to print all the values. You will also need to overload a few operators (==, !=, <, >, <<)
#include <string>
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
class timeStamp {
int sec;
int min;
int hr;
public:
explicit timeStamp(string str);
string toString() const;
void print() const;
bool operator==(const timeStamp& other) const;
bool operator!=(const timeStamp& other) const;
bool operator<(const timeStamp& other) const;
bool operator>(const timeStamp& other) const;
};
ostream& operator<<(ostream& os, const timeStamp& ts)
{
os << ts.toString();
return os;
}
timeStamp::timeStamp(string str)
{
sec = stoi(str.substr(0,2));
min = stoi(str.substr(2,2));
hr = stoi(str.substr(4,2));
if (sec >= 60) {
sec -= 60;
min++;
}
if (min >= 60) {
min -= 60;
hr++;
}
}
string timeStamp::toString() const
{
stringstream ss;
ss << setw(2) << setfill('0') << sec << setw(2) << min<< setw(2) << hr;
return ss.str();
}
void timeStamp::print() const
{
cout << setw(2) << setfill('0') << hr << ':' << setw(2) << min << ':' << setw(2) << sec;
}
bool timeStamp::operator==(const timeStamp& other) const
{
return sec == other.sec && min == other.min && hr == other.hr;
}
bool timeStamp::operator!=(const timeStamp& other) const
{
return !(*this == other);
}
bool timeStamp::operator<(const timeStamp& other) const
{
if (hr < other.hr)
return true;
if (hr > other.hr)
return false;
if (min < other.min)
return true;
if (min > other.min)
return false;
if (sec < other.sec)
return true;
return false;
}
bool timeStamp::operator>(const timeStamp& other) const
{
if (*this < other)
return false;
if (*this == other)
return false;
return true;
}
int main() {
timeStamp ts1("123456");
timeStamp ts2("654321");
cout << "ts1: ";
ts1.print();
cout << endl << "ts2: ";
ts2.print();
cout << endl;
if (ts1 == ts2)
cout << "ts1 == ts2" << endl;
if (ts1 != ts2)
cout << "ts1 != ts2" << endl;
if (ts1 < ts2)
cout << "ts1 < ts2" << endl;
if (ts1 > ts2)
cout << "ts1 > ts2" << endl;
cout << endl << ts1 << " " << ts2 << endl;
}
Comments
Leave a comment