/* phone.cpp * CS401 - Intro to Comp Sci * * This program reads information about phone calls from a file and * displays that information on the screen. * * Each line in the data file should consist of information about one * call. The format is as follows: * * caller-name callee-name cost start-hr start-min end-hr end-min * (string) (string) (doub) (int) (int) (int) (int) * * Strings will not contain any spaces and the cost is per minute. * */ #include #include #include #include #include #include using namespace std; void openInputFile(ifstream&); void displayTime(ostream&, int, int, bool=false); int main() { // set up the input file ifstream fin; openInputFile(fin); // prepare the output format for the cost now cout << setiosflags(ios::fixed) << setprecision(2); // work through fin while (! fin.eof()) { // these hold the information about the call being processed string caller, callee; double cost; int shr, smin, ehr, emin; // load a call (one line in the input file) fin >> caller >> callee // no spaces in the names, so this is ok >> cost >> shr >> smin >> ehr >> emin; // display the call information on the screen cout << caller << " called " << callee << " at " << cost << " per minute\n the call started at "; displayTime(cout, shr, smin); cout << " and ended at "; displayTime(cout, ehr, emin, true); // this clears out any whitespace in fin - we have to do this or // fin.eof() will not be true when it should be fin >> ws; } fin.close(); cout << "\n\npress a key.\n"; getch(); return 0; } // this function will prepare f for input by getting the name from the user // and opening the file void openInputFile(ifstream &f) { string s; cout << "Enter data file name: "; getline(cin, s, '\n'); f.open(s.c_str()); // we have to convert s to a c string for it to work if (!f) { cout << "could not find input file.\n"; getch(); exit(-1); } cout << "file opened successfully.\n\n"; return; } // this function prints the time (h:m) to the output stream given // the third argument (cr) is optional and it represents whether or not to // insert a carriage return at the end of the time - the default value is // false (see the prototype for the default declaration) void displayTime(ostream& out, int h, int m, bool cr) { out << h << ":"; if (m < 10) out << 0; // gives things like 1:05 and not 1:5 out << m; if (cr) out << endl; return; }