Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

suppose a Time class is declaired: class Time{ public: void printTime() const; p

ID: 3729117 • Letter: S

Question

suppose a Time class is declaired:

class Time{

public:

void printTime() const;

private:

int hour, minute, second;

};

define the member function printTime() to print th etime in 12-hour format (with AM or PM) appended as appropriate. For example, 07:15:00 should print as 7:15:00 AM and 13:03:05 should print as 1:30:05 PM. Also define a constructor for time that creates a time structure from input specified in the 12-hour format. The constructor prototype is declared by:

Time(int h, int m, int s, string AM_PM);

the AM_PM parameter is either "AM" or "PM"

Explanation / Answer

#include <iostream>
#include <string>

class Time {
public:
Time(int h, int m, int s, std::string AM_PM); // constructor prototype
void printTime(); // member function
private:
int hour,minute,second;
};

//12-hour format (with AM or PM) appended as appropriate.
Time::Time(int h, int m, int s, std::string AM_PM):
hour(h), minute(m), second(s)
{
if (AM_PM == "AM" && hour == 12)
hour = 0;
if (AM_PM == "PM" && hour != 12)
hour += 12;
}

void Time::printTime()
{
if (hour == 0 || hour == 12)
std::cout << "12";
else
std::cout << hour % 12;
std::cout << ':' << minute << ':' << second;

if (hour / 12 == 0)
std::cout << " AM";
else
std::cout << " PM";
}

// main function
int main()
{
using namespace std;
cout << "Input should be specified in the 12-hour or 24-hour format";
cout << ' ';
cout << "Enter the time (hour,minute,second): ";
int hour, minute, second;
cin >> hour >> minute >> second;
string AM_PM;
Time t(hour, minute, second, AM_PM);
t.printTime();
cout << ' ';

return 0;
}

/*

output:

Input should be specified in the 12-hour or 24-hour format                                                                   

Enter the time (hour,minute,second): 13                                                                                      

30                                                                                                                           

50                                                                                                                           

1:30:50PM

*/