落書きノート

ふと自分が気になった事を書いてます

C++で問題を解く

今回は1問だけです。

#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>

class Time {
    int h;
    int m;
    int s;
public:
    Time();
    Time(const int& h, const int& m = 0, const int& s = 0);
    
    int getHour() const { return this->h; }
    int getMinute() const { return this->m; }
    int getSecond() const { return this->s; }

    Time one_sec_ago() const;
    std::string to_string() const;
};

std::ostream& operator<<(std::ostream& s, const Time& x);
std::istream& operator>>(std::istream& s,       Time& x);

using namespace std;

Time::Time(){
    this->h = 12;
    this->m = this->s = 0;
}

Time::Time(const int& h, const int& m, const int& s){
    this->h = h;
    this->m = m;
    this->s = s;
}

Time Time::one_sec_ago() const {
    Time temp = *this;

    if(temp.s > 0)
        temp.s--;
    else {
        temp.s = 59;
        if(temp.m > 0)
            temp.m--;
        else {
            temp.m = 59;
            if(temp.h > 0)
                temp.h--;
            else
                temp.h = 23;
        }
    }

    return temp;
}

string Time::to_string() const {
    ostringstream ss;
    ss << setfill('0')
        << setw(2) << h << "時" << setw(2) << m << "分" << setw(2) << s << "秒";
    return ss.str();
}

ostream& operator<<(ostream& s, const Time& x){
    return s << x.to_string();
}

istream& operator>>(istream& s, Time& x){
    int hh,mm,ss;
    char ch;

    s >> hh >> ch >> mm >> ch >> ss;
    x = Time(hh, mm, ss);
    return s;
}

int main(void){
    Time c;

    cout << "時刻c : ";
    cin >> c;

    cout << "その時刻の文字列表現は\"" << c.to_string() << "\"です。" << endl;
    cout << "その時刻の1秒前は" << c.one_sec_ago() << "です。" << endl;

    return 0;
}