This worked perfectly fine for me:
Code:
#include <iostream>
#include <fstream>
#include <ctime>
using namespace std;
time_t start, end;
struct tm *IN, *OUT;
double diff;
void timeIN() {
time (&start); //Get the current time
IN = localtime (&start); //Adjust to the local timezone
cout << "Time in: " << asctime (IN); //Print the time IN
}
void timeOUT() {
time (&end); //Get the current time
OUT = localtime (&end); //Adjust to the local timezone
cout << "Time out: " << asctime (OUT); //Print the time OUT
}
void timeWORKED() {
diff = (difftime (end, start))/3600; //Calculate the number of hours worked
cout << "Hours worked: " << diff << "\n";
}
void outPUT() {
cout << "Outputting to timeworked.txt\n";
ofstream workFile ("timeworked.txt"); //Open timeworked.txt for output
if ( !workFile.is_open() ) { //Check to see if the file is not open
cout << "Error: Failed to open file\n"; //If the file is not open give an Error
} //Otherwise output the data to the file
else {
workFile << "Time in: " << asctime (IN);
workFile << "time out: " << asctime (OUT);
workFile << "Hours worked: " << diff << "\n";
workFile.close();
}
}
void error() {
cout << "Error!!!\n";
}
void menu() {
int opt;
cout << "[1] Enter your time IN \n";
cout << "[2] Enter your time OUT \n";
cout << "[3] Calculate your total time Worked\n";
cout << "[4] Output to a file\n";
cout << "[5] Exit\n";
cout << "Enter your choice: ";
cin >> opt;//you need error checking and recover here!
switch ( opt ) {
case 1: timeIN(); break;
case 2: timeOUT(); break;
case 3: timeWORKED(); break;
case 4: outPUT(); break;
case 5: exit(0);
default: error();
}
}
int main() {
while (1) {
menu();
}
return 0;
}