include <iostream>
#include <cmath>
#include <iomanip>
#include <string>
using namespace std;
class Time {
public:
void readTime(bool & errFlag);
int subtractTimes(Time t);
private:
int minutes;
};
void Time::readTime(bool & errFlag)
{
enum period { AM, PM } T_Period;
int hr;
int mn;
char period;
errFlag = true;
if (!(cin >> hr))
return;
if (hr < 0 || hr > 12)
return;
cin >> period;
if (!(cin >> minutes))
return;
if (mn < 0 || mn > 59)
return;
cin >> period;
if (period == 'A' || period == 'a')
T_Period = AM;
else if (period == 'P' || period == 'p')
T_Period = PM;
else
return;
cin >> period;
if (period != 'M' && period != 'm')
return;
errFlag = false;
if (hr == 12)
minutes = mn;
else
minutes = hr * 60 + mn;
if (T_Period == PM)
minutes += 60 * 12;
}
int Time::subtractTimes(Time t)
{
return minutes - t.minutes;
}
int main()
{
int totalTimeTravelled(0);
double totalHourTravelled, totalSpeed;
double distance = -1;
bool valid = false;
char answer;
do {
bool errFlag;
Time startTime, stopTime;
cout << "\nEnter the start time (ex. 11:00am): ";
startTime.readTime(errFlag);
while (errFlag) {
cout << "Invalid formatted input, please try again: ";
startTime.readTime(errFlag);
}
cout << "Enter the stop time: ";
stopTime.readTime(errFlag);
while (errFlag) {
cout << "Invalid formatted input, please try again: ";
stopTime.readTime(errFlag);
}
totalTimeTravelled += stopTime.subtractTimes(startTime);
do
{
cout << "Enter the distance (mile): ";
cin >> distance;
if (cin.good())
{
valid = true;
}
else
{
cin.clear();
cout << "\t" << distance << " is not a valid distance. Try again! \n";
}
} while (!valid);
cout << "Would you like to calculate the speed? (y/n):";
cin >> answer;
totalHourTravelled = (double)totalTimeTravelled / 60;
totalSpeed = distance / totalHourTravelled;
} while (answer != 'y');
if (totalSpeed < 0)
{
cout << "Total speed of your trip shows " << setprecision(2) << fixed << totalSpeed << " mph. \n" << "However, your speed is mathematically incorrect! \n\n";
}
else
{
cout << "Total speed of your trip is " << setprecision(2) << fixed << totalSpeed << " mph. \n\n";
}
system(pause);
return 0;
}