写了一个时钟程序,如何在输出的时候在不足两位的数上补0?
问题:写了一个时钟程序,如何在输出的时候在不足两位的数上补0?#include<iostream>
using namespace std;
class Time{
private:
int hour;
int min;
int sec;
public:
friend ostream & operator<<(ostream &output,Time&);
friend istream & operator>>(istream &input,Time&);
Time operator+(Time &c);
Time operator-(Time &c);
friend Time operator++(Time &);
friend Time operator--(Time &,int);
bool operator> (Time &c);
bool operator< (Time &c);
bool operator== (Time &c);
};
istream & operator>>(istream &input,Time &c){ //输入
cout<<"请输入时分秒:"<<endl;
input>>c.hour>>c.min>>c.sec;
if((c.hour<0||c.hour>=60)||(c.min<0||c.min>=60)||(c.sec<0||c.sec>=60)){
c.hour=0;
c.min=0;
c.sec=0;
cout<<"输入错误"<<endl;
exit(0);
}
return input;
}
ostream& operator<<(ostream &output,Time &c){ //输出
output<<c.hour<<':'<<c.min<<':'<<c.sec;
return output;
}
Time Time::operator+(Time &c){//加
Time t(*this);
if(t.sec+c.sec>=60){
t.sec=t.sec+c.sec-60;
++t.min;
}else{
t.sec=t.sec+c.sec;
}
if(t.min+c.min>=60){
t.min=t.min+c.min-60;
++t.hour;
}else{
t.min=t.min+c.min;
}
if(t.hour+c.hour>=24){
t.hour=t.hour+c.hour-24;
}else{
t.hour=t.hour+c.hour;
}
return t;
}
Time Time::operator-(Time &c){//减
Time t(*this);
if(t.sec<c.sec){
t.sec=t.sec+60-c.sec;
--t.min;
}else{
t.sec=t.sec-c.sec;
}
if(t.min<c.min){
t.min=t.min+60-c.min;
--t.hour;
}else{
t.min=t.min-c.min;
}
if(t.hour<c.hour){
t.hour=t.hour+24-c.hour;
}else{
t.hour=t.hour+-c.hour;
}
return t;
}
Time operator++(Time &c){
c.hour++;
return c;
}
Time operator--(Time &c,int){
Time temp(c);
c.hour--;
return c;
}
bool Time::operator> (Time &c){
if(hour>c.hour) return true;
else if((hour==c.hour) && (min>c.min)) return true;
else if((hour==c.hour) && (min==c.min) && (sec > c.sec)) return true;
return false;
}
bool Time::operator< (Time &c){
if(hour<c.hour) return true;
else if((hour==c.hour) && (min<c.min)) return true;
else if((hour==c.hour) && (min==c.min) && (sec < c.sec)) return true;
return false;
}
bool Time::operator== (Time &c){
if((hour==c.hour) && (min==c.min) && (sec == c.sec)) return true;
return false;
}
int main(){
Time t1, t2, t;
cin >> t1 >> t2;
cout << "t1为:" << t1 << endl;
cout << "t2为:" << t2 << endl;
t = t1 + t2;
cout << "t1+t2=" << t << endl;
t = t1 - t2;
cout << "t1-t2=" << t << endl;
if (t1 > t2) cout << "t1>t2" << endl;
if (t1 < t2) cout << "t1<t2" << endl;
if (t1 == t2) cout << "t1==t2" << endl;
++t1;
cout<<"++t1= ";
cout<<t1<<endl;
cout<<"t1--= ";
t1--;
cout<<t1<<endl;
}
试试用setfill()函数 栗粒粒 发表于 2020-4-4 12:15
试试用setfill()函数
先用setw(2)保证两位的输出,再用setfill(0)补0
页:
[1]