// average2A2.cpp
// Averages a sequence of integers input from
// a text file specified by the user.
// The number of numbers to be averaged is the
// first number in the text file, followed by
// the numbers to be averaged.
// The filename is entered interactively
// by the user as a C-string.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// Announce purpose of program:
cout << "This program averages a sequence of integers "
<< "in a file specified by you." << endl << endl;
// Obtain filename from user input, as a C-string:
char filename[20]; // C-string with up to 19 characters
cout << "Enter filename: ";
cin >> filename;
// Prepare to read from file:
ifstream inputFile;
inputFile.open(filename);
// Input, error check, and echo
// number of numbers to be averaged:
int numberOfNumbers;
inputFile >> numberOfNumbers;
if ( numberOfNumbers <= 0 )
{
cout << "The number of numbers, " << numberOfNumbers
<< ", is invalid. Must be > 0." << endl;
return 1;
} // if
cout << numberOfNumbers
<< " numbers will be averaged" << endl << endl;
// Cumulative sum:
int sum = 0;
// Input and echo numbers to be averaged,
// and add them to cumulative sum:
int count = 0;
while ( count < numberOfNumbers )
{
int number;
inputFile >> number;
cout << number << endl;
sum += number;
count++;
} // while
// Compute the average and output the result:
float average = (float) sum / numberOfNumbers;
cout << endl << "The average is: "
<< average << "." << endl;
return 0;
} // function main