Finding Average from text file.

Hi! Say I have a text file, like this:

1
2
3
4
5
6
Joe 15
Joe 16
Joe 15
Bob 12
Bob 13
Bob 13


and so on, in alphabetical order, with each student achieving different scores in different tests. How may I find the average score of each student? I've already set up a part of the code which will sort the student's names alphabetically, thus grouping them together. I'm just not sure how I can go about doing this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <ifstream>
using namespace std;

int main()
{
ifstream yoFile;
char fileName[50];
cout << "Enter your file name. DON't forget the extension";
cin.getline(fileName,50);
yoFile.open(fileName);
if (!yoFile.is_open()) {
     cout << "Text file failure.";
       }
int value;
int sum;
int count;
while(yoFile.good()){
 ++count;
sum +=value;
yoFile >> value;
      }
if (yoFile.eof()){
   cout << "All fruits have been read! Average score is " << sum/count << ".";
   }
}

I haven't tested this btw.
@Zarman I don't think you read the question properly. It doesn't ask you to average all the values, but instead the average for each student (there are different students in the files).
Plus simply posting code with no explanation or without properly testing, doesn't help anybody.

@jakobfri, can we see what you have? You said you already had part of the code to sort students names, and if you did it properly this shouldn't be too hard to modify to accept numerical inputs as well.

Also perhaps some more details on the rules of the file would be helpful in providing an efficient answer as opposed to a more general answer.

For example, if the file is in a strict form of:
[Student A] [grade]
[Student A] [grade]
[Student A] [grade]
...
[Student B] [grade]
[Student B] [grade]
[Student B] [grade]
...

and the student information is not mixed it is possible to use two sets of vectors one containing the student name, and the other containing the average which is calculated as you read each sequential line in the file.

However if the file follows this format:
[Student A] [grade]
[Student B] [grade]
[Student A] [grade]
[Student C] [grade]
[Student B] [grade]
...

And there is no apparent order in the way students and their grade data is contained in the file then you can use a map, which uses the name of the student as the key and a vector or some other type of container containing the list of grades for that student, you could also keep a vector of the names to keep track of the keys (aka names). At the end of the file just run through the map using the vector of keys, and calculate the average for each student.
This however, can be improved in terms of efficiency, and you can try and see how exactly to improve the efficiency of this method.
yup I didn't read it carefully. sorry
Topic archived. No new replies allowed.