// Reading an unknown number of lines of data from a file
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

int main ()
{
  string source = "kelvin.tmp";   // source file
  string target = "degrees.tmp";  // target file

  ifstream kelvin(source.c_str());
  ofstream degrees(target.c_str());

  // Check if files can be opened
  if ( ! kelvin.is_open() ) {
    cout << "Unable to open file " << source << endl;
    return 1; // stop the execuation of the program
  }
  if ( ! degrees.is_open() ) {
    cout << "Unable to open file " << target << endl;
    return 1;
  }

  double s = 0.0, mean, k, c;
  int n = 0;

  cout << "Reading data from file: " << source << endl;
  cout << "Writing data to file: "   << target << endl;

  // Start an infinte loop
  while(1)
  {
      kelvin >> k;                // Read a line from source file
      if( kelvin.eof() ) break;   // Do you reach end of file?
      c = k + 273.15;             // Convert
      degrees << setw(8) << fixed // Write to the target file
              << setprecision(2)
              << c << endl;
      s += k;                     // Sum the temperatures
      n++;                        // Count number of lines
  }                               // Goto next line in the file

  kelvin.close();                 // Close the files
  degrees.close();

  mean = s/n;
  cout << "number of data   = " << n << endl;
  cout << "mean of the data = " << mean << endl;

  return 0;
}
