1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
|
#include <iostream>
#include <string>
using namespace std;
class Time
{
private:
int hr;
int min;
int sec;
public:
Time(); // nice to have this too
Time(const int &h, const int &m, const int &s);
int getHour() const;
int getMinutes() const;
int getSeconds() const;
void setHour(const int &hour);
void setMinutes(const int &mins);
void setSeconds(const int &secs);
void showTime();
};
Time::Time(const int &h, const int &m, const int &s)
{
/* hr = h;
min = m;
sec = s;*/
setHour(h); // see setHour below.
setMinutes(m);
setSeconds(s);
}
Time::Time(){};
// getters
int Time::getHour() const
{
return hr;
}
// Do same for minutes and seconds
// Ensure that the hour value is in the range 0 – 23; if it is not, set the hour to 12.
void Time::setHour(const int &hour)
{
if(hour >= 0 && hour <= 23){
hr = hour;
}
else{
hr = 12;
}
}
// Ensure that the minute value is in the range 0 – 59; if it is not, set the minute to 0
void Time::setMinutes(const int &mins)
{
// do the control here
}
// Ensure that the second value is in the range 0 – 59; if it is not, set the second to 0
void Time::setSeconds(const int &secs)
{
// do the control here
}
/*
if hr, sec and min are < 10, append "0" to it otherwise use it as is
see http://www.cplusplus.com/reference/string/to_string/
*/
void Time::showTime()
{
string time;
string h, m, s;
if(hr < 10){
h = "0" + to_string(hr);
}else{
h = to_string(hr);
}
if(min < 10){
m = "0" + to_string(min);
}else{
m = to_string(min);
}
if(sec < 10){
s = "0" + to_string(sec);
}else{
s = to_string(sec);
}
cout << "Time is : " << h << ":" << m << ":" << s << endl;
}
int main()
{
// test show time
Time t = Time(1,3,4);
t.showTime();
Time t1 = Time(12,9,34);
t1.showTime();
Time t2 = Time(-2, -2, 23);
t2.showTime();
cout << " Please enter each integer as two digits." << endl;
cout << " Enter hours: ";
int h;
cin>> h;
cout << " Enter minutes: ";
int m;
cin>> m;
cout << "Enter Seconds: ";
int s;
cin>> s;
Time t3 = Time(h,m,s);
t3.showTime();
// or using your setters
Time t4; // this will call Time::Time(){};
t4.setHour(h);
t4.setMinutes(m);
t4.setSeconds(s);
t4.showTime();
return 0;
}
|