Directly Add code
Define the header file:
//: C09: Cpptime. h
// From Thinking in C ++, 2nd Edition
// Available at http://www.BruceEckel.com
// (C) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// A simple time class
# Ifndef CPPTIME_H
# Define CPPTIME_H
# Include <ctime>
# Include <cstring>
Class Time {
Time_t t;
Tm local;
Char asciiRep [26];
Unsigned char lflag, aflag;
Void updateLocal (){
If (! Lflag ){
Local = * localtime (& t );
Lflag ++;
}
}
Void updateAscii (){
If (! Aflag ){
UpdateLocal ();
Strcpy (asciiRep, asctime (& local ));
Aflag ++;
}
}
Public:
Time () {mark ();}
Void mark (){
Lflag = aflag = 0;
Time (& t );
}
Const char * ascii (){
UpdateAscii ();
Return asciiRep;
}
// Difference in seconds:
Int delta (Time * dt) const {
Return int (difftime (t, dt-> t ));
}
Int daylightSavings (){
UpdateLocal ();
Return local. tm_isdst;
}
Int dayOfYear () {// Since January 1
UpdateLocal ();
Return local. tm_yday;
}
Int dayOfWeek () {// Since Sunday
UpdateLocal ();
Return local. tm_wday;
}
Int since1900 () {// Years since1900
UpdateLocal ();
Return local. tm_year;
}
Int month () {// Since January
UpdateLocal ();
Return local. tm_mon;
}
Int dayOfMonth (){
UpdateLocal ();
Return local. tm_mday;
}
Int hour () {// Since midnight, 24-hour clock
UpdateLocal ();
Return local. tm_hour;
}
Int minute (){
UpdateLocal ();
Return local. tm_min;
}
Int second (){
UpdateLocal ();
Return local. tm_sec;
}
};
# Endif // CPPTIME_H ///:~
Example:
//: C09: Cpptime. cpp
// From Thinking in C ++, 2nd Edition
// Available at http://www.BruceEckel.com
// (C) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Testing a simple time class
# Include "head. h"
# Include <iostream>
Using namespace std;
Int main (){
Time start;
For (int I = 1; I <1000; I ++ ){
Cout <I <'';
If (I % 10 = 0) cout <endl;
}
Time end;
Cout <endl;
Cout <"start =" <start. ascii ();
Cout <"end =" <end. ascii ();
Cout <"delta =" <end. delta (& start );
}///:~
From yucan1001