//*****************************************************************
// R. A. Hillyard
// fileAvg4.cpp 
// March 2001
//
// This version uses a function to open the files
//*****************************************************************

#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

void setDecimalPoint(ostream& coutForMe, int places);
bool openFiles(ifstream& inFile, ofstream& outFile);

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;
    
  if(!openFiles(scoreFile, avgFile))  //open files and exit if problem
    {
    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
  
bool openFiles(ifstream& inFile, ofstream& outFile)
  {
  inFile.open("scores.dat");     //open the file
  if(inFile.fail())              //check for success and exit if open failed
    {
     cout << "unable to open scores.dat file\n";
    return false;
    }

  outFile.open("average.dat");   //open the file
  if(outFile.fail())             //check for success and exit if open failed
    {
    cout << "unable to open average.dat file\n";
    return false;
    }
  return true;
  }

//*********************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