// average5A.cpp
// Averages a sequence of integers input from a
// text file specified by the user.
// The numbers are read to end of file.
// Error state of file input stream is checked
// after file is opened and after all file inputs.
// This program uses a break statement in the loop,
// eliminating some repetition of code.
#include <iostream>
#include <fstream>
#include <iomanip>
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[21]; // C-string with up to 20 characters
cout << "Enter filename: ";
cin.getline(filename, 20);
// Prepare to read from file:
ifstream inputFile;
inputFile.open(filename);
// Check whether file exists and is readable:
if ( !inputFile )
{
cout << "Can't read file "
<< filename << "." << endl;
return 1;
} // if
// Announce input:
cout << "Now reading numbers from file "
<< filename << ":" << endl << endl;
// Cumulative sum:
int sum = 0;
int count = 0;
// Input the numbers to be averaged,
// echo them, and add them all to
// cumulative sum, until end of file:
while ( true )
{
// Input a number:
int number;
inputFile >> number;
// Exit loop when end of file is reached.
// Avoid processing the non-number.
if ( !inputFile )
break;
// Echo the most recently read number:
cout << setw(15) << number << endl;
// Add current number to cumulative sum:
sum += number;
// Increment count of numbers entered so far:
count++;
} // while
// Prevent division by zero:
if ( count == 0 )
{
cout << "You didn't enter any numbers." << endl;
return 1;
} // if
// Compute the average and output the result:
float average = (float) sum / count;
cout << endl << "The average is: "
<< average << "." << endl;
return 0;
} // function main