//***************************************************************** // R. A. Hillyard // fileAvg2.cpp // October 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& myStream, int palces); int main() { long int idnum; //variable for id number int mid1, mid2, final; //variables for test scores double avg; //variable for average score 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 scoreFile >> idnum >> mid1 >> mid2 >> final; while (!scoreFile.eof()) { 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 scoreFile >> idnum >> mid1 >> mid2 >> final; }//endwhile scoreFile.close(); //close files avgFile.close(); return 0; }
/**************************************************************/ void setDecimalPoint(ostream& myStream, int palces) { myStream.setf(ios::showpoint); //set percision for decimal numbers myStream.setf(ios::fixed); myStream.precision(palces); } /* //*********************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 */