|
Hi , i think this is the same problem a fellow class member has written about. But ,this program calculates the time elapsed between two clock times entered at the command line. I have completed it however there is something wrong with my error checking function setTime() at present when entering" start time: 7 30 ,Finish time: 7 29 "the elapsed time is suppose to be 23:59 however mine is 0 : -1. Specifying 1 minute instead of 23 hours and 59 minutes. If i put in other time such as 7 30 to 23 30 it does calculate the time correctly at 16: 0 hours. Oh and it is meant to return an Error code if the time entered is in an incorrect format-which i cannot get it to do either, any ideas?
include <iostream> using namespace std;
struct Mytime { int hours; int mins; };
int timecmp( Mytime, Mytime );
int setTime( Mytime& t, int h, int m ); // if valid time sets hh and mm to h and m // and returns 0 // if invalid returns integer > 0 as error code // error code +1 = underflow hours // error code +2 = overflow hours // error code +4 = underflow mins // error code +8 = overflow mins
void display1Time( Mytime t );
void elapsed( Mytime t1, Mytime t2, Mytime& duration );
int main() { Mytime now; Mytime then; Mytime howlong; int h,m; do // validate input { cout << "Enter start hh mm : "; cin >> h >> m ; } while (setTime(now,h,m)); do { cout << "Enter finish hh mm : "; cin >> h >> m ; } while (setTime(then,h,m)); elapsed(now,then,howlong);
cout << "Time elapsed from "; display1Time(now); cout << " until "; display1Time(then); cout << " is "; display1Time(howlong); cout << endl; return ( 0 ); }
int timecmp(Mytime t1,Mytime t2) { if (t1.hours == t2.hours) { if (t1.mins == t2.mins) { return 0; } else // mins not same { if (t1.mins > t2.mins) { return 1; // greater than zero } else { return -1; } } } else // hours not same { if (t1.hours > t2.hours) { return 1; } else { return -1; } } }
int setTime(Mytime& t, int h, int m ) { t.hours = h; t.mins = m; if (t.hours >= 0 && t.hours <= 23) { if (t.mins >= 0 && t.mins <= 60 ) { return 0; } } else // Data invalid {
if (t.hours < 0) { cerr << "+1" << endl; // Error code returned } else if (t.hours > 23 ) { cerr << "+2" << endl; else if( t.mins < 0)
{ cerr << "+4" << endl; }
if (t.mins > 60 ) { cerr << "+8" << endl; } else { return 0; }
} }
void display1Time(Mytime t) { cout << t.hours << ":" << t.mins; //Displays calculated time }
void elapsed(Mytime t1, Mytime t2, Mytime& duration) { duration.hours = t2.hours - t1.hours; duration.mins = t2.mins -t1.mins;// Time elapsed calculated } i have adapted the code to include the error checking, it is working however not correctly
This post has been edited by Tara200: 27 Jan, 2008 - 02:38 PM
|