How to find average of multiple rows within a text file.

Write your question here.
Hello! I am having trouble finding out how to read a file and find an average for the 10 rows of numbers. I already have the file opened, but I do not know the right commands to proceed. The text file name is "lab1.txt". I then need to store the 10 averages in a vector to use later in the program.

The Text file contains:
70 79 72 78 71 73 68 74 75 70
78 89 96 91 94 95 92 88 95 92
83 81 93 85 84 79 78 90 88 79
93 100 86 99 98 97 96 95 94 92
72 60 82 64 65 63 62 61 67 64
80 92 100 81 82 83 84 85 86 87
92 91 74 76 77 78 81 83 80 88
67 60 65 68 72 74 76 77 78 73
93 99 91 93 94 96 95 97 98 74
82 81 89 75 77 79 81 83 85 78


Just read 10 numbers, summing them up, and divide by 10. Do that 10 times, storing the results in your vector.
1
2
3
4
5
6
7
8
9
10
11
12
vector<double> averages;
for (int i = 0; i < 10; ++i)
{
  int sum = 0;
  for (int j = 0; j < 10; ++j)
  {
    int n;
    fin >> n;
    sum += n;
  }
  averages.push_back(sum / 10.0);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
...
std::vector<double> v_averages;  // instantiates an empty vector
std::string tmp;
while ( std::getline( my_file, tmp ) )  // reads a whole line
{
    std::istringstream iss( tmp ); // copies the string into 
    int total = 0;
    int number;
    while( iss >> number )  // extract the numbers
    {
         total += number;
    }
    v_averages.push_back( total / 10.0 );  // appends the average to the vector
}
...
Last edited on
Topic archived. No new replies allowed.