1. 程式人生 > >第五週專案3 時間類的練習(1)

第五週專案3 時間類的練習(1)

/* 
 *Copyright(c) 2016,煙臺大學計算機學院 
 *All rights reserved. 
 *檔名稱:test2.cpp 
 *作    者:劉金石 
 *完成日期:2016年3月29日 
 *版本  號:v1.0 
 *問題描述:時間類的練習。
 *輸入描述:無。 
 *輸出描述:輸出時間。 
*/  
<pre name="code" class="cpp">/*
 *Copyright(c) 2016,煙臺大學計算機學院
 *All rights reserved.
 *檔名稱:test2.cpp
 *作    者:劉金石
 *完成日期:2016年3月29日
 *版本  號:v1.0
 *問題描述:時間類的練習。
 *輸入描述:無。
 *輸出描述:輸出時間。
*/
#include<iostream>
using namespace std;
class Time
{
public:
    void set_time();
    void show_time();
    void add_a_sec()
    {
        sec+=1;
    }
    void add_a_minute()
    {
        minute+=1;
    }
    void add_a_hour()
    {
        hour+=1;
    }
private:
    bool is_time(int ,int ,int );
    int hour,minute,sec;
};
void Time::set_time()
{
    char c1,c2;
    cout<<"請輸入時間(格式hh:mm:ss)";
    while(1)
    {
        cin>>hour>>c1>>minute>>c2>>sec;
        if(c1!=':'||c2!=':')
            cout<<"格式不正確重輸"<<endl;
        else if(!is_time(hour,minute,sec))
            cout<<"時間非法!請重新輸入:"<<endl;
        else
            break;
    }
}
void Time::show_time()
{
    cout<<"時分秒各加一後:"<<endl;
    if(!is_time(hour,minute,sec))
        cout<<"時間非法!"<<endl;
     else cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
bool Time::is_time(int h,int m,int s)
{
    if(h<0||h>24||m<0||m>60||s<0||s>60)
        return false;
    return true;
}
int main()
{
    Time t1;
    t1.set_time();
    t1.add_a_sec();
    t1.add_a_minute();
    t1.add_a_hour();
    t1.show_time();
    t1.set_time();
    t1.add_a_sec();
    t1.add_a_minute();
    t1.add_a_hour();
    t1.show_time();
    return 0;
}

執行結果: