/* * 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 "apstring.h" void OpenInput( apstring & infile, ifstream & fin ); void ProcessFile( istream & fin ); int main( ) { apstring 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( apstring & infile, ifstream & fin ) { for( ; ; ) // Loop until a break { cout << "Enter the input file name: "; cin >> infile; fin.open( infile.c_str( ), ios::in | ios::nocreate ); 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; apstring Name; apstring 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; }