64,637
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <cctype>
#include <cstdlib>
//#include "dtime.h"
using namespace std;
class DigitalTime
{
public:
friend bool operator ==(const DigitalTime &time1,const DigitalTime& time2);
DigitalTime(int the_hour,int the_minute);
DigitalTime();
void advance(int minutes_added);
void advance(int hours_added,int minutes_added);
friend istream& operator >>(istream& ins,DigitalTime the_object);
friend ostream& operator <<(ostream& outs,const DigitalTime the_object);
private:
int hour;
int minute;
};
void read_hour(istream& ins,int& the_hour);
void read_minute(istream& ins,int& the_minute);
bool operator ==(const DigitalTime& time1,const DigitalTime& time2)
{
return (time1.hour==time2.hour && time2.minute==time2.minute);
}
DigitalTime::DigitalTime(int the_hour,int the_minute)
{
if(the_hour<0 || the_minute<0)
{
cout<<"Illegal time!\n";
system("pause");
exit(1);
}
hour=the_hour;
minute=the_minute;
}
DigitalTime::DigitalTime():hour(0),minute(0)
{}
void DigitalTime::advance(int hours_added,int minutes_added)
{
int new_hours,new_minutes;
new_minutes=minute+minutes_added;
minute=new_minutes%60;
new_hours=hour+hours_added+new_minutes/60;
hour=new_hours%24;
}
void DigitalTime::advance(int minutes_added)
{
int gross_minutes=minute+minutes_added;
minute=gross_minutes%60;
int hour_adjustment=gross_minutes/60+hour;
hour=hour_adjustment%24;
}
ostream& operator <<(ostream& outs,const DigitalTime& the_object)
{
outs<<the_object.hour<<":";
if(the_object.minute<10)
outs<<'0';
outs<<the_object.minute;
return outs;
}
istream& operator >>(istream& ins,DigitalTime& the_object)
{
read_hour(ins,the_object.hour);
read_minute(ins,the_object.minute);
return ins;
}
int digit_to_int(char c)
{
return (c-'0');
}
void read_hour(istream& ins,int& the_hour)
{
char c1,c2;
ins>> c1>>c2;
if(!(isdigit(c1) && isdigit(c2) || c2==':'))
{
cout<<"Error illegal input to read_hour.\n";
system("pause");
exit(1);
}
if(c2==':')
the_hour=digit_to_int(c1);
else
{
the_hour=digit_to_int(c1)*10 + digit_to_int(c2);
ins>>c2;
if(c2!=':')
{
cout<<"Error illegal input to read_minute.\n";
system("pause");
exit(1);
}
}
if(the_hour>24 || the_hour<0)
{
cout<<"Error illegal input to read_hour.\n";
system("pause");
exit(1);
}
}
void read_minute(istream& ins,int& the_minute)
{
char c1,c2;
if(!isdigit(c1) || !isdigit(c2))
{
cout<<"Error illegal input to read_minute.\n";
system("pause");
exit(1);
}
the_minute=digit_to_int(c1)*10 + digit_to_int(c2);
if(the_minute<0 || the_minute>60)
{
cout<<"Error illegal input to read_minute.\n";
system("pause");
exit(1);
}
}