Overloaded insertion operator to display the Time in the form hr:min:sec. If hours, minutes
and/or seconds is a single digit, the time should be shown as 0x: where x is hours, minutes or
seconds. Example: 02:33:45, 13:05:66, 23:17:09
#include <iostream>
class Time {
private:
int hours;
int minutes;
int seconds;
public:
Time() : hours(0), minutes(0), seconds(0) {}
Time(int _hours, int _minutes, int _seconds)
: hours(_hours), minutes(_minutes), seconds(_seconds) {}
friend std::ostream& operator <<(std::ostream& os, const Time& time) {
if (time.hours / 10 == 0) {
os << "0";
}
os << time.hours << ":";
if (time.minutes / 10 == 0) {
os << "0";
}
os << time.minutes << ":";
if (time.seconds / 10 == 0) {
os << "0";
}
os << time.seconds;
return os;
}
~Time() {}
};
int main() {
int hours, minutes, seconds;
std::cout << "Enter hours, minutes, seconds separated with space:\n";
std::cin >> hours >> minutes >> seconds;
Time t(hours, minutes, seconds);
std::cout << t << '\n';
return 0;
}
Comments
Leave a comment