Skip to content

Instantly share code, notes, and snippets.

@EteimZ
Created January 4, 2023 21:47
Show Gist options
  • Select an option

  • Save EteimZ/e92e9bf331ab53652dc99c4acd2f594f to your computer and use it in GitHub Desktop.

Select an option

Save EteimZ/e92e9bf331ab53652dc99c4acd2f594f to your computer and use it in GitHub Desktop.
Time class implementation in cpp gotten from the book C How to program.
// program to run class Time
#include <iostream>
using std::cout;
using std::endl;
#include "Time.h"
int main(){
Time t; // instantiate a Time object of class Time
// output Time object t's initial values
cout << "The initial universal time is ";
t.printUniversal(); // 00:00:00
cout << "\nThe initial standard time is ";
t.printStandard(); // 12:00:00 AM
t.setTime(13, 14, 56 ); // change time
// output Time object t's new values
cout << "\n\nUniversal time after setTime is ";
t.printUniversal(); // 13:14:56
cout << "\nStandard time after setTime is ";
t.printStandard(); // 1:14:56
t.setTime(99, 99, 99); // attempt invalid settings
// output t's values after specify ing invalid values
cout << "\n\nAfter attempting invalid setting:"
<< "\nUniversal time: ";
t.printUniversal(); // 00:00:00
cout << "\nStandard time: ";
t.printStandard(); // 12:00:00 AM
cout << endl;
return 0;
}
// Member-function definitions for class Time
#include <iostream>
using std::cout;
#include <iomanip>
using std::setfill;
using std::setw;
#include "Time.h" // include definition of class Time from Time.h
// intialize data members to zero
Time::Time(){
hour = minute = second = 0;
}
// set new time using universal time;
// To ensure data consistency all invalid values are set to 0
void Time::setTime( int h, int m, int s ){
hour = ( h >= 0 && h < 24 ) ? h : 0; // validate hour
minute = ( m >= 0 && m < 60 ) ? m : 0; // validate minute
second = ( s >= 0 && s < 60 ) ? s : 0; // validate second
}
// Print time in universal time format
void Time::printUniversal(){
cout << setfill( '0' ) << setw( 2 ) << hour << ":"
<< setw( 2 ) << minute << ":" << setw( 2 ) << second;
}
// Print time in standard time format
void Time::printStandard(){
cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) << ":"
<< setfill( '0' ) << setw( 2 ) << minute << ":" << setw( 2 )
<< second << ( hour < 12 ? " AM" : " PM" );
}
// Declaration of class Time
// Member functions defined in Time.cpp
// prevent multiple inclusion of header file
#ifndef TIME_H
#define TIME_H
// Time class definition
class Time{
public:
Time(); // constructor
void setTime( int, int, int ); // set hour, minute and second
void printUniversal(); // print time in universal-time format
void printStandard(); // print time in standard-time format
private:
int hour; // 0 - 23 (24-hour clock format)
int minute; // 0 - 59
int second; // 0 - 59
}; // End class Time
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment