Answer to Question #177806 in C++ for sabbir

Question #177806

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 (==, !=, <, >, <<)


1
Expert's answer
2021-04-02T19:08:28-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS