/* Homework 3, see http://cs.fit.edu/~mmahoney/cse1502/ Matt Mahoney This program reads a time from the user of the form hh:mm:ss in the range 00:00:00 to 99:59:59 and a file containing a list of times, elevations, and temperatures (as doubles), with times in ascending order, for example: 00:03:00 500 16.5 00:04:00 550 17.5 00:04:30 570 17 01:44:30 870 -3 If the user enters a time that matches a line of the file, then the program prints the elevation and temperature from that line. If the user time is between two lines then it interpolates the value. If it is before the first line or after the last, then it prints an error, for example, if the above file is named balloon3.txt, then: Enter time: 00:04:00 Enter file name: balloon3.txt Elevation is 550 Temperature is 17.5 Enter time: 00:03:30 Enter file name: balloon3.txt Elevation is 525 Temperature is 17 Enter time: 00:04:20 Enter file name: balloon3.txt Elevation is 563.333 Temperature is 17.1667 Enter time: 01:34:30 Enter file name: balloon3.txt Elevation is 840 Temperature is -1 Enter time: 00:02:59 Enter file name: balloon3.txt Error: time is before first reading. Enter time: 01:45:00 Enter file name: balloon3.txt Error: time is after last reading. Enter time: 00:04:00 Enter file name: balloon4.txt Error: file balloon4.txt not found. */ #include // cin, cout, endl #include // ifstream #include // string #include // exit using namespace std; // Returns interpolated value f(b) given a, b, c // on x axis and f(a), f(c) on y axis. double interpolate(double a, double b, double c, double fa, double fc) { return fa + (fc-fa)/(c-a) * (b-a); } int main() { // Read user time int hr, min, sec; char colon; cout << "Enter time (hh:mm:ss) : "; cin >> hr >> colon >> min >> colon >> sec; int b = hr*3600 + min*60 + sec; // user time // Get file name from user cout << "Please enter file name: "; string filename; cin >> filename; // Open file and check for file not found ifstream in(filename.c_str()); if (!in) { cout << "File not found: " << filename << endl; exit(0); } double elev=0, temp=0; // from current line of file double last_elev, last_temp; // from previous line int a=0, c=0; // previous and current time in sec. bool first=true; // first line of file? while (true) { // Save previous line of file a = c; last_elev = elev; last_temp = temp; // Read current line of file if (!(in >> hr >> colon >> min >> colon >> sec >> elev >> temp)) { // error (too late) cout << "Error: time is after last reading\n"; break; } c = hr*3600 + min*60 + sec; // current time if (c > b) { if (first) { // too soon cout << "Error: time is before first reading\n"; break; } else { // interpolate cout << "Elevation is " << interpolate(a, b, c, last_elev, elev) << "\n"; cout << "Temperature is " << interpolate(a, b, c, last_temp, temp) << "\n"; break; } } else if (c == b) { // match cout << "Elevation is " << elev << "\n" << "Temperature is " << temp << "\n"; break; } first=false; } return 0; }