/*  Program name: files.cpp - for demonstrating file input/output
 *
 *  Date: September 2005
 */

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

void main() {
	char inputChoice;
	double num;

	do {
		cout << "Would you like to read or write to a file? Type W or R, then Enter: ";
		cin >> inputChoice;
	} while ( !(inputChoice=='w' || inputChoice=='W' || inputChoice=='r' || inputChoice=='R'));

	if (inputChoice=='w' || inputChoice=='W'){

		//Open a file for output, to write to
		ofstream outputFile;

		outputFile.open("numbers.txt"); //Open the file for writing
		if(outputFile.fail()) {
			cout << "Error: could not open" << endl;
			exit(1);
		}

		cout << "Enter a list of numbers, then 0 to finish"<<endl;
		do{
			cout << "Enter a number: ";
			cin >> num;
			outputFile << num << endl;  //Write to the file
		} while (num!=0);

		outputFile.close();  //Close the file
		cout << "Your numbers have been written to the file." <<endl;
	}// end if W
  
	if (inputChoice=='R' || inputChoice=='r'){
		double total;
		int count;
		double average;

		ifstream inputFile;

		inputFile.open("numbers.txt"); //Open the file for reading
		if(inputFile.fail()) {
			cout << "Error: could not open" << endl;
			exit(1);
		}

		//Initialize total and count
		total=0;
		count=0;

		//Read the numbers
		do {
			inputFile >> num;
			if (num!=0){
				total += num;
				count++;
			}
		} while (num!=0);

		inputFile.close();  //Close the file

		cout << "There were "<< count << " numbers read." << endl;
		cout << "Total = " << total << endl;
		average = total/count;
		cout << "Average = " << average <<endl << endl;
	}// end if R
} //end main()