/* * Read a file that contains lines of the form * Name salary * Output the number of lines read the average salary, * and the highest-salaried person. * This program is deliberately missing comments. */ #include #include #include using namespace std; void openInput( string & infile, ifstream & fin ); void processFile( istream & fin ); int main( ) { string infile; // Input file name ifstream fin; // Input file stream openInput( infile, fin ); processFile( fin ); return 0; } /** * Prompt the user for an input file and open it. * (Differs from the day class version in that it informs * the user of the name of the file that was opened. * This is used in sample #2.) * Pre: None. * Post: fin is open and ready for reading. * infile is the name of the file that was opened. */ void openInput( string & infile, ifstream & fin ) { for( ; ; ) // Loop until a break { cout << "Enter the input file name: "; cin >> infile; fin.open( infile.c_str( ) ); if( !fin ) // !fin true if open fails { cout << "Bad file." << endl; // Print message fin.clear( ); // Reset the error state } else break; } } /** * Process the file. Print the number of people read, * the average salary, and the person with the high salary. * pre: fin is open and ready for reading. * lines contain a name and salary. * post: the required info is output, and fin has been read completely. */ void processFile( istream & fin ) { int itemsRead = 0; double sum = 0.0; string name; string richBoy; double salary; double maxSalary = 0.0; while( fin >> name >> salary ) { itemsRead++; sum += salary; if( salary > maxSalary ) { maxSalary = salary; richBoy = name; } } cout << "Read " << itemsRead << " records." << endl; cout << "The average salary is " << (sum / itemsRead) << endl; cout << "The highest paid person is " << richBoy << "; "; cout << "(s)he makes " << maxSalary << endl; }