Hello, I am having a hard time with a loop for pulling information from a txt file and averaging it together.
My problem is that the loop only reads one line and then quits, so it is only averaging one number.
the program prints all the data and then shows the total and averages as shown below:
Bailey Y 16 68
Harrison N 17 71
Grant Y 20 75
Peterson N 21 69
Hsu Y 20 79
Bowles Y 15 75
Anderson N 33 64
Nguyen N 16 68
Sharp N 14 75
Jones Y 29 75
McMillan N 19 80
Gabriel N 20 62
the total is 68
the average is 68
My Code looks like this:
// This program reads a file of numbers.
// It calculates the total and the average.
// Written by: Robert Brown
// Sources: Class Text, Lecture Videos
// Date: 23-October-2009
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
// Declarations
char a;
string reply;
double number;
double totalUnder18, totalOver18;
int count, age;
string inputFileName;
ifstream inputFile;
string line;
string name;
cout << fixed << showpoint << setprecision(2);
cout << "Input file name: ";
getline(cin, inputFileName);
// Open the input file.
inputFile.open(inputFileName.c_str()); // Need .c_str() to convert a C++ string to a C-style string
// Check the file opened successfully.
if ( ! inputFile.is_open()) {
cout << "Unable to open input file." << endl;
cout << "Press enter to continue...";
getline(cin, reply);
exit(1);
}
// This section reads and echo's the file one line at a time.
while (inputFile.peek() != EOF) {
getline(inputFile, line);
cout << line << endl;
}
cout << "\nEnd of file reached\n" << endl;
// Must clear the end-of-file flag to be able to rewind and re-read from the beginning.
inputFile.clear();
// 'Rewind' the input stream to the beginning - i.e. byte 0
inputFile.seekg(0);
count = 0; // Must initialize the counter to zero
totalUnder18 = 0; // Must initialize the accumulator to zero.
while (inputFile >> name){
while (inputFile >> a)
while (inputFile >> age)
while (inputFile >> number)
totalUnder18 += number;
count++; // Increment the counter
}
cout << "The total is: " << setw(11) << totalUnder18 << endl;
// Be careful not to divide by zero!
if (count > 0) {
cout << "The average is: " << setw(9) << totalUnder18/count << endl;
}
cout << "Press enter to continue...";
getline(cin, reply);
return 0;
}
Any help would be much appreciated
Thanks!