问题描述:
利用组合类,写出闹钟程序。一个类定义为clock,用于接收用户输入的时间,并返回时间字符串。再定义一个类alarm_clock,clock的对象是其私有成员。其功能是实现当前时间的动态输出,并且实现到点就响铃。
代码展示:
#include<iostream>
#include<time.h>
#include<string.h>
#include<string>
#include<windows.h>
using namespace std;
//建立时钟类 功能是可以由用户输入时间并返回一个string类型的字符串
class Clock {
private:
char *Week, *Month;
int D, H, M, S;
public:
Clock(const char *wp, const char *mp, int D, int H, int M, int S)
{
//Clock类的构造函数 用来接收用户输入的时间
Week = new char[3];
Month = new char[3];
strcpy(Week, wp);
strcpy(Month, mp);
this->D = D;
this->H = H;
this->M = M;
this->S = S;
}
Clock()
{
}
string gettime()
{
char timep[25];
sprintf(timep, "%s %s %d %d:%d:%d 2021", Week, Month, D, H, M, S);
string t = timep;
return t;
}
};
//定义一个闹钟的组合类 里面的私有数据是一个时钟类
class alarm_clock {
private:
Clock EndTime;
char *etime; //建立字符数组用来接收字符串
public:
void show()
{
cout << etime[0];
}
alarm_clock(Clock S)
{
EndTime = S;
}
void exchange() //用来将时钟类传进的string类型转换成char类型
{
etime = new char[25];
string a; //建立string数据类型变量a用来接收时钟类传来的字符串
a = EndTime.gettime();
a.copy(etime, 24, 0);
*(etime + 24) = '\0';
}
void alarm() //闹钟类中的公有成员函数 目的是动态显示当前时间 并判断是否响铃
{
exchange();
string a = EndTime.gettime();
int d;
char tmp[25];
time_t curtime;
while (1)
{
time(&curtime);
for (d = 0; d < 24; d++)
tmp[d] = ctime(&curtime)[d];
tmp[d] = '\0'; //第一次读取时间赋给tmp
if (strcmp(etime, tmp) <= 0)
{
cout << "叮铃铃!!!" << endl;
cout << "\a";
}
cout << tmp << endl;
Sleep(1000);
}
}
};
int main()
{
char *week, *month;
week = new char[3];
month = new char[3];
int da, h, m, s;
cout << "请输入闹钟响铃的具体日期(周 月 日 时 分 秒)" << endl;
cout << "例如:Sat Oct 16 08:30:30" << endl;
cin >> week >> month >> da >> h >> m >> s;
Clock C1(week, month, da, h, m, s);
alarm_clock C2(C1);
C2.alarm();
}
问题总结:
在实现时间的动态显示时,要调用Sleep()函数,实现程序的延迟运行,对应的头文件为windows.h
在比较两个时间字符串是否一样时,一定要确保两个字符串只有时间值不一样,其余全相等。