// readfromfile.cpp - how to read from a text file
#include <iostream>
// We need to include fstream to have access to file manipulation
// commands, and the ifstream class. 
#include <fstream>

int main() {
  using namespace std;
  int count=0;
  int sum=0;
  int val=0;

  // creating an ifstream variable and associating a file with it.
  ifstream inFile;
  inFile.open("stats.txt");
  
  if (inFile.is_open()) {

    // the good() function returns true if nothing went wrong.
    // therefore use it in a while loop to read until EOF
    while(inFile.good()) {
      count++;
      inFile >> val;
      sum += val;
      cout << "Value = " << val << ", Sum = " << sum << "\n";
    }
    
    // check to see if the while loop ended because of an eof 
    // or a type mismatch / failure.
    if (inFile.eof()) {
      cout << "End of file reached.\n";
    }
    else if (inFile.fail()) {
      cout << "Input terminated by a type mismatch.\n";
    }

    // output file read results.
    cout << endl;
    cout << "There were " << count << " items read.\n";
    cout << "The sum of these values is " << sum << ".\n";
    
    inFile.close();
  
  }
  else {

    cout << "No file by that name.\n";

  }

}

