// average2B2.cpp
// Averages a sequence of integers input from
// a text file specified by the user.
// The number of numbers to be averaged is the
// first number in the text file, followed by
// the numbers to be averaged.
// The filename is entered interactively
// by the user as a C-string.
// Error state of file input stream is checked
// after file is opened and after all file inputs.

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

int main()
{
   // Announce purpose of program:
   cout << "This program averages a sequence of integers "
             << "in a file specified by you." << endl << endl;

   // Obtain filename from user input, as a C-string:
   char filename[20];   // C-string with up to 19 characters
   cout << "Enter filename: ";
   cin >> filename;

   // Prepare to read from file:
   ifstream inputFile;
   inputFile.open(filename);

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

   // Input, error-check, and echo
   // the number of numbers to be averaged:
   int numberOfNumbers;
   inputFile >> numberOfNumbers;
   if ( !inputFile )
   {
      cout << filename << " file data format error: "
               << "Can't read number of numbers." << endl;
      return 1;
   }  // if
   if ( numberOfNumbers <= 0 )
   {
      cout << "The number of numbers, " << numberOfNumbers
             << ", is invalid.  Must be > 0." << endl;
      return 1;
   }  // if
   cout << numberOfNumbers
            << " numbers will be averaged" << endl << endl;

   // Cumulative sum:
   int sum = 0;

   // Input and echo numbers to be averaged,
   // and add them to cumulative sum:
   int count = 0;
   while ( count < numberOfNumbers )
   {
      // Input, error-check, and echo the current number:
      int number;
      inputFile >> number;
      if ( !inputFile )
      {
         cout << filename << " file data format error: "
               << "Not reading " << numberOfNumbers
                      << " consecutive integers." << endl;
         return 1;
      }  // if
      cout << number << endl;

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

      // Count numbers added to sum so far:
      count++;
   }  // while

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

   return 0;
}  // function main