I wanna write a program that tests the tick member function in a loop that prints the time during each iteration of the loop to illustrate that the tick member function works correctly.
Here What I wrote so far :
#include <iostream>
#include <iomanip>
using namespace std;
class Time
{
public:
Time(int = 0, int = 0, int = 0);
void setTime(int, int, int);
void setHour(int);
void setMinute(int);
void setSecond(int);
int getHour();
int getMinute();
int getSecond();
void printTime();
void Tick();
private:
int hour;
int minute;
int second;
};
Time::Time(int hour, int minute, int second)
{
setTime(hour, minute, second);
}
void Time::setTime(int h, int m, int s)
{
setHour(h);
setMinute(m);
setSecond(s);
}
void Time::setHour(int h)
{
hour = (h >= 0 && h < 24) ? h : 0;
}
void Time::setMinute(int m)
{
minute = (m >= 0 && m < 60) ? m : 0;
}
void Time::setSecond(int s)
{
second = (s >= 0 && s < 60) ? s : 0;
}
int Time::getHour()
{
return hour;
}
int Time::getMinute()
{
return minute;
}
int Time::getSecond()
{
return second;
}
void Time::printTime()
{
cout << setfill('0') << setw(2) << hour << ":" << setw(2) << minute << ":" << setw(2) << second << endl;
}
################################
void Time::Tick()
{
second++;
if (second == 60)
{
second = 0;
minute++;
}
if (minute == 60)
{
minute = 0;
hour++;
}
}
################################
int main ()
{
Time t;
t.setTime(14,59,59);
t.Tick();
t.printTime();
return 0;
}
this code ticks just once. How can it tick by one second every time I run the program ?? First run : 14:00:00
Second run : 14:00:01
Third run : 14:00:02
A program doesn't remember its values from one run to the next. Even if it did, this program would still generate the same answer every time because you set the time to 14:59:59 and then call Tick(). The result of those two calls will always be 15:00:00.
I think what you want to do is put a loop around the Tick() and printTime() functions so that it calls each of those several times.
If you really need it to remember the value from one run to the next then you have to write the value of t out to a file when you're done and read it back in at the beginning.