program that takes two values of time (hr, min,Sec) and outputs their sum using constructor and operator overloading.
#include <iostream>
#include <iomanip>
#include <cstring>
#include <sstream>
using namespace std;
class Time
{
private:
int hours;
int minutes;
int seconds;
public:
Time()
{
hours = minutes = seconds = 0;
}
Time(int hours, int minutes, int seconds)
{
if (hours < 0)
throw string("Invalid number of hours.");
if (minutes < 0 || minutes >= 60)
throw string("Invalid number of minutes.");
if (seconds < 0 || seconds >= 60)
throw string("Invalid number of seconds.");
this->hours = hours;
this->minutes = minutes;
this->seconds = seconds;
}
string ToString()
{
ostringstream oss;
oss.width(2);
oss.fill('0');
oss << setw(2) << setfill('0') << hours << ":"
<< setw(2) << setfill('0') << minutes << ":"
<< setw(2) << setfill('0') << seconds;
return oss.str();
}
Time operator + (const Time& time)
{
int totalSeconds = this->seconds + time.seconds;
int totalMinutes = this->minutes + time.minutes;
int totalHours = this->hours + time.hours;
totalMinutes += totalSeconds / 60;
totalHours += totalMinutes / 60;
totalSeconds %= 60;
totalMinutes %= 60;
return Time(totalHours, totalMinutes, totalSeconds);
}
static Time Input(istream& stream)
{
int h, m, s;
stream >> h >> m >> s;
return Time(h, m, s);
}
};
int main()
{
Time time_1, time_2;
bool error;
cout << "Enter first time (hours minutes seconds): ";
error = true;
while (error)
{
try
{
time_1 = Time::Input(cin);
}
catch (string e)
{
cout << " " << e << " Please re-enter (hours minutes seconds): ";
continue;
}
error = false;
}
cout << "Enter second time (hours minutes seconds): ";
error = true;
while (error)
{
try
{
time_2 = Time::Input(cin);
}
catch (string e)
{
cout << " " << e << " Please re-enter (hours minutes seconds): ";
continue;
}
error = false;
}
cout << endl;
cout << "The sum is: " << (time_1 + time_2).ToString() << 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!
Learn more about our help with Assignments:
C++