组合类闹钟

该博客介绍了一个C++程序,它定义了两个类,`Clock`和`alarm_clock`。`Clock`类用于接收用户输入的时间并返回时间字符串,而`alarm_clock`类作为`Clock`的组合类,具有动态显示当前时间并实现到点响铃的功能。程序通过`Sleep()`函数实现延迟,并使用字符串比较来判断是否达到设定的闹钟时间。
摘要由CSDN通过智能技术生成

问题描述:

利用组合类,写出闹钟程序。一个类定义为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

在比较两个时间字符串是否一样时,一定要确保两个字符串只有时间值不一样,其余全相等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值