// average6.cpp

#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char** argv)
{
   // Check command-line arguments and
   // display instructions if necessary:
   if ( argc < 2 )
   {
      cout << "This program averages a sequence of "
                     << "integers in a file specified" << endl;
      cout << "as a command-line argument." << endl;
      return 0;
   }  // if

   // Prepare to read from file:
   ifstream inputFile;
   inputFile.open(argv[1]);

   // Check whether file exists and is readable:
   if ( !inputFile )
   {
      cout << "Can't read file "
               << argv[1] << "." << endl;
      return 1;
   }  // if

   // Count of the number of numbers to be averaged:
   int numberOfNumbers = 0;
 
   // Cumulative sum:
   int sum = 0;

   // Input and echo numbers to be averaged,
   // and add them to cumulative sum:
   do  {
      // Input the current number:
      int number;
      inputFile >> number;
      if ( inputFile )
      {
         // Echo current number:
         cout << number << endl;

         // Add current number to cumulative sum
         // and update count of numbers:
         sum = sum + number;
         numberOfNumbers++;
      }  // if
   } while ( inputFile );

   // Compute the average and output the result:
   float average = ( numberOfNumbers == 0 )
                   ? 0
                   : (float) sum / numberOfNumbers;
   cout << endl << "The average is: "
                << average << "." << endl;

   // Print good-bye message:
   cout << "Thank you for using " << argv[0] << "." << endl;

   return 0;
}  // function main