Search code examples
c++fstream

Summarize then average every 10 lines from a txt file


I have this code for the task mentioned in the title:

The program reads from a 1 columned text file in which the numbers are below each other.

#include <iostream>
#include <fstream>

using namespace std;

int main()
{

    double number;
    double sum = 0;

    ifstream average;
    average.open("average.txt");

    while (average >> number)
    {
        for(int i = 0; i < 10; i++)
        {
            sum = sum + number;

            i++;

            if (i = 9)
            {
                cout << sum / 10 << endl;
            }
         }
    {

    average.close();
    system("pause");
    return 0;
}

But somehow it doesn't average the numbers just divide all of them by 10.

What might be the problem?

Thanks


Solution

  • A possible solution:

    int i;
    while (average.good()) // only while we are good
    {
      sum = 0; // you need to clean it
      for(i = 0; i < 10; i++)
      {   
        average >> number;
    
        if (!average.good()) break; // if number of lines is not mod10
    
        sum = sum + number;
        // i++; you already do that in for loop
      }
      if (i)
      {
        cout << sum / i << endl; // only print after each 10 or less
      }
    }
    

    Or with the single loop:

    sum = 0;
    int i = 0;
    
    while (average >> number) {
      sum = sum + number;
      ++i;
    
      if (i == 10) {
        cout << sum / i << endl;
        sum = i = 0;
      }
    }
    if (i) {
      cout << sum / i << endl;
    }