// average8.cpp
// Averages a sequence of integers input from a
// text file specified via a command-line argument.
// Error state of file input stream is checked
// after file is opened and after all file inputs.

#include <iostream>
#include <fstream>
#include <iomanip>
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.  In the file, "
                     << "the number of numbers in the" << endl;
      cout << "sequence must be specified before the "
                     << "first number in the sequence." << 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

   // Announce input:
   cout << "Now reading numbers from file "
         << argv[1] << ":" << endl << endl;

   // Cumulative sum:
   int sum = 0;
   int count = 0;

   // Input the first number:
   int number;
   inputFile >> number;

   // Input more numbers to be averaged,
   // echo them, and add them all to
   // cumulative sum, until end of file:
   while ( inputFile )
   {
      // Echo the most recently read number:
      cout << setw(15) << number << endl;

      // Add current number to cumulative sum:
      sum += number;

      // Increment count of numbers entered so far:
      count++;

      // Input the NEXT number:
      inputFile >> number;
   }  // while

   // Prevent division by zero:
   if ( count == 0 )
   {
      cout << "You didn't enter any numbers." << endl;
      return 1;
   }  // if

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

   return 0;
}  // function main