Answer to Question #329995 in C++ for Bambo

Question #329995

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

1
Expert's answer
2022-04-18T08:40:34-0400
#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;
}

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