// dynamicArray.cc   Demo of reading into dynamic array from file
// P. Conrad for CISC181, 06S

// sample command line: ./dynamicArray 500 nums.dat

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

int main(int argc, char *argv[])
{
  if (argc!=3)
    {
      cerr << "Usage: " << argv[0] << " maxNumberElems filename" << endl;
      exit(1);
    }

  int maxNumberElems = atoi( argv[1] );

  // try to open the input file
  
  ifstream infile(argv[2],ios::in);

  // if file could not be opened, print error message and exit

  if (!infile)
    {
      cerr << "Error: Could not open " << argv[2] << endl;
      exit(2);
    }

  // read the data into the array

  int x;
  int count=0;

  // allocate an array from the heap with exactly maxNumberElems elements

  int *nums = new int [maxNumberElems];

  infile >> x;

  // keep processing while there is more data, and while there is still room

  while (!infile.eof() && count < maxNumberElems) 
    {
      // store data in array
      nums[count] = x;
      count ++;

      infile >> x;
    }

  if (!infile.eof())
    {
      cerr << "Error: Some of your data was ignored; your maxNumElems was too small. " << endl;
      exit(3);
    }


  // use array
  
  for (int i=0; i<count; i++)
    {
      cout << "nums[" << i << "]=" << nums[i] << endl;
    }

  return 0;
}
