//头文件
#ifndef ALARM_H
#define ALARM_H
using namespace std;
class Alarm
{
public:
int menu_select();//菜单选择
void dispaly_time();//显示时间
bool set_time();//设定预报的时间
bool is_non_time(int aHour, int aMin);//判断时间合法性
bool tell_time(int aHour, int aMin);//按照时间报时
private:
int m_iHour;
int m_iMin;
};
#endif
源文件
// alarm.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <windows.h>
#pragma comment(lib, "winmm.lib")
#include "alarm.h"
int Alarm::menu_select()
{
cout << " 迷你小闹钟 "<<endl <<"1.显示当前时间"<<endl<<"2.设定时间"<<endl<<"0.退出"<<endl;
cout <<"请选择(0-2)"<<endl;
int choice;
for (;;)
{
cin >> choice;
if (choice<0||choice>2)
{
cout << "输入的选择错误!!请重新输入0-2!";
}
else
switch (choice)
{
case 1:
dispaly_time();
break;
case 2:
set_time();
break;
case 0:
exit(0);
default :
break;
}
}
return choice;
}
void Alarm::dispaly_time()
{
time_t rawtime;//获取时间种子
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );//当地时间
cout << "现在北京时间为: "<<timeinfo->tm_year +1900<<"年"<<
timeinfo->tm_mon+1<<"月"<<timeinfo->tm_mday<<"日/t" <<
timeinfo->tm_hour<<":"<<timeinfo->tm_min<<":"<<
timeinfo->tm_sec<<endl;
}
bool Alarm::is_non_time(int aHour, int aMin)
{
if (aHour<24&&aHour>=0)
{
if (aMin>=0&&aMin<60)
{
return true;
}
}
cout << "你输入的时间不合法!!"<<endl; set_time();
}
bool Alarm::set_time()
{
int aHour,aMin,aSec;
cout << "请设定要报时的时间(用空格隔开):";
cin >> aHour>>aMin;
is_non_time(aHour,aMin);
m_iHour=aHour;
m_iMin=aMin;
tell_time(m_iHour,m_iMin);
return true;
}
bool Alarm::tell_time(int aHour,int aMin)
{
time_t rawtime;//获取时间种子
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );//当地时间
long long differ;//现在相差多少时间
differ=(timeinfo->tm_hour-aHour)*3600+(timeinfo->tm_min)*60;
cout <<"Zzz Zzz····";
Sleep(differ);//sleep()毫秒
cout <<"懒虫快起床!!!" <<endl;
PlaySound (TEXT ("C://1.wav"), NULL, SND_FILENAME | SND_ASYNC) ;
dispaly_time();
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
Alarm clock;
clock.menu_select();
system("pause");
return 0;
}
运行结果: