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!

:D

line 41: That is a horrible way to test for eof -- all you need is this:

while( getline(inputFile, line) )
{
    cout << line << '\n';
}

lines 55-60: WTF??? You can not code nested while loops like that and expect anything other than the results you got.

while( inputFile >> name >> a >> age >> number)
{
   // blabla
}

Thank you Ancient Dragon. I made the changes and have some nested if/else loops to determine four different averages, however the program is not pulling the last number from the file so the average is coming out yo zero ecause 0/1 = 0.

here is a simplified data file i amusing to debug with:

rob y 17 20
joe n 16 15
melissa n 26 50
jeff y 35 17

here is the output i am recieving:


Input file name: myresults2.txt
rob y 17 20
joe n 16 15
melissa n 26 50
jeff y 35 17

End of file reached

The average for subjects under 18 and who have not seen the ad is: 15.00
The average for subjects under 18 and who have seen the ad is: 20.00
The average for subjects over 18 and who have not seen the ad is: 50.00
The average for subjects over 18 and have seen the ad is: 0.00
Press any key to continue...

And finally here is the code i am using:

// 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 totalUnder18N, totalUnder18Y,  totalOver18N, totalOver18Y;
    int countUnder18N, countUnder18Y, countOver18N, countOver18Y, 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 (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);
    
    countUnder18N = 0;
    countUnder18Y = 0;
    countOver18N = 0;
    countUnder18Y = 0;       // Must initialize the counter to zero
    totalUnder18N = 0;       // Must initialize the accumulator to zero.
    totalUnder18Y = 0;
    totalOver18Y = 0;
    totalOver18N = 0;
    
        while (inputFile >> name >> a >> age >> number){
            if ((a == 'Y' || a == 'y') && (age < 18))
            {
               countUnder18Y++;  
               totalUnder18Y += number;
            } 
                else if ((a == 'N' || a == 'n') && (age < 18))
                {
                     countUnder18N++;
                     totalUnder18N += number;
                }
                     else if ((a == 'Y' || a == 'y') && (age >= 18))
                     {
                          countOver18Y++;
                          totalOver18Y += number;
                     }
                          else if ((a == 'N' || a == 'n') && (age >= 18))
                          {
                               countOver18N++;
                               totalOver18N += number;
                          }}
            
            if (countUnder18N > 0)
            {
              cout << "The average for subjects under 18 and who have not seen the ad is: " << setw(9) << totalUnder18N/countUnder18N << endl;
            }
               else 
                {
                    cout << "the average for subjects under 18 who have not seen the ad is undefined." << endl;
                }
            
            if (countUnder18Y > 0)
            {
              cout << "The average for subjects under 18 and who have seen the ad is: " << setw(9) << totalUnder18Y/countUnder18Y << endl;
            }
               else
                {
                    cout << "the average subjects under 18 and who have seen the ad is undefined." << endl;
                }
            
            if (countOver18N > 0)
            {
              cout << "The average for subjects over 18 and who have not seen the ad is: " << setw(9) << totalOver18N/countOver18N << endl;
            }
               else
                {
                    cout << "the average subjects over 18 and who have not seen the ad is undefined." << endl;
                }
            
            if (countOver18Y > 0)
            {
              cout << "The average for subjects over 18 and have seen the ad is: " << setw(9) << totalOver18Y/countOver18Y << endl;
            }
               else
                {
                    cout << "the average for subjects over 18 and have seen the ad is undefined." << endl;
                }
            
    
    cout << "Press enter to continue...";
    getline(cin, reply);
    return 0;	
}

Thank you for all your help Ancient Dragon. I was able to fix my last mistake on my own, i initialized the same variable twice which caused my error. Problem solved...Thanks again!

commented: ++ for working out the solution to the problem youself. :) +24
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.