File input program

Hi all.

I'm supposed to write a program that reads info (name, gender, school, and test scores) from a file and outputs the average test scores of different groups (males, university students, etc.).

I've done a lot of reading but am still pretty stumped in a lot of ways.

I know I need to use a while loop so the program keeps reading data until the end of the file, but I don't know how set it up so the program saves the data as the appropriate type and can read several lines of data without having a variable for each piece of data.

For example, if I have a line in the input file like this:

Johnson F UN 89

I need to be able to use that score of 89 to figure out average scores for all females.

I know I'm not giving you a lot to go on, but any help you could give me would be great. Thank you.
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <sstream>
#include <ifstream>
#include <vector>

struct entry
{
    std::string name;
    char gender;
    std::string school;
    int score;
};

int main()
{
    std::vector<entry> database;
    std::ifstream fin("input.txt");
    std::string line;
    
    while( getline(fin, line) )
    {
        std::stringstream iss(line);
        entry temp;
        line >> temp.name;
        line >> temp.gender;
        line >> temp.school;
        line >> temp.score;
        
        database.push_back(temp);
    }
    
    //Now you have a vector with all of your data!
    
    double average = 0;
    int nb_females = 0;
    for (std::vector<entry>::iterator it = database.begin(); it != database.end(); ++it)
    {
        if (it->gender == 'F')
        {
            ++nb_females;
            average += it->score;
        }
    }
    average /= nb_females;
    
    // now average represents the actual average.
}
Last edited on
Ok, I definitely need to bone up on my vectors, but that works great. Thank you!
Topic archived. No new replies allowed.