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.
#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.
}