// prg42.cpp

// Calculate the sum of all numbers stored in a file.
// The program does not know the number of items stored
// in the file in advance.

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

int main()
{
  ifstream input_file; // input file stream
  string fname;    // file name
  int x;           // data value
  int sum;         // sum of all data values

  cout << "Input file name ? ";
  cin >> fname;

  input_file.open(fname.c_str());

  if(!input_file) {
    cout << "Error: Can't open file." << endl;
    return 1;
  }

  sum = 0; // initialize
  // if the following statement fails, ``input_file'' will be set to false.
  input_file >> x; 
  while(input_file) {  // input_file is false if EOF (end of file) is reached
    cout << x << endl; // print out the value just read
    sum = sum + x;     // add the value to sum
    input_file >> x;   // read the next value 
  }

  input_file.close();
 
  cout << "The sum of all numbers in the file is " << sum << ".\n";

  return 0;
}

// We can also use the condition: !input_file.eof() for the loop.

