1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
|
#include <iostream>
#include <fstream>
#include<string>
#include <cstdlib>
using namespace std;
bool parseTime(char* _timeStr, int& _hour, int& _min)
{
// Make sure a pointer was passed in
if (NULL == _timeStr)
return false;
// Hours starts at the string passed in, minutes we figure out in a second
char* hourStr = _timeStr;
char* minStr = NULL;
// Loop through the string looking for the : character
char* curChar = _timeStr;
while (*curChar)
{
if (':' == *curChar)
{
// Found our minutes string. NULL terminate the hour string and set the minute string.
*curChar = '\0';
minStr = curChar + 1;
break;
}
++curChar;
}
// If no minute string was found, error
if (NULL == minStr)
return false;
// Convert the strings to integers and store them
_hour = atoi(hourStr);
_min = atoi(minStr);
// Restore the : character (could also use the "curChar" variable for this, but this way is more fun)
*(minStr - 1) = ':';
// Test for invalid values
if (_hour < 0 || _hour > 23)
return false;
if (_min < 0 || _min > 59)
return false;
// Theoretical success!
return true;
}
int main ()
{
char time1[80];
char time2[80];
std::ofstream outfile;
string line;
string name;
int totaltimeused;
ofstream myfile;
myfile<<totaltimeused;
myfile.close();
cout<<"Enter your name :";
cin>>name;
if(name=="a")
{
ifstream myfiles ("herald.txt");
if (myfiles.is_open())
{
while ( getline (myfiles,line) )
{
cout << line << '\n';
}
myfiles.close();
}else{
cout << "Unable to open file"; }
cout<<"Time in: ";
cin >> time1;
cout<<"Time out: ";
cin >> time2;
int hour1, min1;
int hour2, min2;
if (!parseTime(time1, hour1, min1))
{
cout << "Error parsing time 1: " << time1 << ". Invalid time format.\n";
return(0);
}
if (!parseTime(time2, hour2, min2))
{
cout << "Error parsing time 2: " << time2 << ". Invalid time format.\n";
return(0);
}
// Hours worked and minutes worked
int hoursWorked = hour2 - hour1;
int minsWorked = min2 - min1;
// It is possible that a full hour was not worked, meaning the minutes would be negative.
if (minsWorked < 0)
{
// If that is the case, deduct one hour and add 60 minutes. Since minutes is negative, this
// yields the actual minutes worked (IE, -4 becomes 56).
--hoursWorked;
minsWorked += 60;
}
cout << "Time worked: " << hoursWorked << " hours, " << minsWorked << " minutes.\n";
myfile.open ("herald.txt",std::ios_base::in);
myfile<< hoursWorked<< "hours,"<< minsWorked <<"minutes.\n";
myfile.close();
return 0;
}
}
|