要求:输入时间进行计时。
代码如下:
#include<iostream>
#include<ctime>
#include<unistd.h>
using namespace std;
class Time{
private:
int h;//小时
int m;//分钟
int s;//秒
public:
Time(int hour,int min,int sec);//构造函数
void run();//运行
void show();//显示
};
Time::Time(int hour,int min,int sec)//构造函数赋初值
{
h = hour;
m = min;
s = sec;
}
void Time::show()
{
cout << '\r';//全部显示在同一行
if(this->h<10) cout << 0;
cout << this->h << ':';
if(this->m<10) cout << 0;
cout << this->m << ':';
if(this->s<10) cout << 0;
cout << this->s << flush;//立刻显示
}
void Time::run()
{
while(h||m||s){//设置程序结束
sleep(1);//等待1S
if(--s<0){
s = 59;
if(--m<0){
m = 59;
--h;
}
}
Time::show();
}
cout << "\nTime out" << endl;
}
int main()
{
int hour,minute,second;
cout << "Please input countdown as \"hour minute second\" " << endl;
cin >> hour >> minute >> second;
Time t(hour,minute,second);
t.run();
return 0;
}
结果: