//***************************************************************** // R. A. Hillyard // fileAvg3.cpp // March 2001 // // // This version writes to an output file as well as the screen //***************************************************************** #include <iostream> #include <fstream> #include <iomanip> using namespace std; void setDecimalPoint(ostream& coutForMe, int places); int main() { long int idnum; //variable for id number int mid1, mid2, final; //variables for test scores ifstream scoreFile; //declare an input file stream ofstream avgFile; scoreFile.open("scores.dat"); //open the file if(scoreFile.fail()) //check for success and exit if open failed { cout << "unable to open file\n"; exit(1); } avgFile.open("average.dat"); //open the file if(avgFile.fail()) //check for success and exit if open failed { cout << "unable to open file\n"; exit(1); } setDecimalPoint(cout, 2); //set precision for output streams setDecimalPoint(avgFile, 2); //read data from file and process while (scoreFile >> idnum >> mid1 >> mid2 >> final) { double avg = (mid1 + mid2 + 2*final) / 4.0; //calculate average cout << idnum << setw(10) << avg << endl; //output result to screen avgFile << idnum << setw(10) << avg << endl; //output result to file }//endwhile scoreFile.close(); //close files avgFile.close(); return 0; } void setDecimalPoint(ostream& coutForMe, int places) { coutForMe.setf(ios::showpoint); coutForMe.setf(ios::fixed); coutForMe.precision(places); }//end setDecimalPoint //*********************contents of scores.dat********************** 123456 82 79 91 234564 88 78 87 976523 91 92 90 782346 77 85 82 987656 62 92 84 345876 77 74 85
//************************program output*************************** 123456 85.75 234564 85.00 976523 90.75 782346 81.50 987656 80.50 345876 80.25
//*********************contents of average.dat********************* 123456 85.75 234564 85.00 976523 90.75 782346 81.50 987656 80.50 345876 80.25