Hi I am working on some homework and I seem to be in a bit of a bind, I keeping hitting a wall, and I have been reading my book and looking for examples that may help, but I am quite unsuccessful.

My Assignment

Pull grades and sexes of people from a file such like this

f
3.25
m
2.56
f
1.82
m
1.95

Then total up the gpa's and the count of the sexes and take the average of each.

Within the file there is know known amount so use EOF

Post out to terminal the Total amount of students, #of females, # of males, and total GPA and Average GPA

So far I think my trouble is trying to read either male of female, and then tyring to read the next line.

So far I have:

``````char character, f, m;
double gpaf, gpam;
double totalfemale = 0;
double totalmale = 0, total;
int countmale = 0, countfemale = 0, counttotal;
double averfemale, avermale, avertotal;

if (!infile)
{
cout << "An error has occurred while opening file" << endl;
exit (1);
}
while (!infile.eof())
{
infile >> character;
if (character == f)
{
infile >> gpaf;
totalfemale = totalfemale + gpaf;
countfemale ++;
}

else if (character == m)
{
infile >> gpam;
totalmale = totalmale + gpam;
countmale ++;
}
}
infile.close();

avermale = totalmale / countmale;
averfemale = totalfemale / countfemale;
total = totalfemale + totalmale;
counttotal = countfemale + countmale;
avertotal = total / counttotal;

cout << "Total Number of Students is " << counttotal << endl;
cout << "Overall Average GPA for Men and Women is " << endl << endl;
cout << "Total Number of Females " << totalfemale << endl;
cout << "Average GPA for Females is " << averfemale << endl << endl;
cout << "Total Number of Males " << totalmale << endl;
cout << "Average GPA for Males is " << avermale << endl;``````

I really appreciate any help you can give me.

Thanks,
Radskate360

A couple of things.

Your input file consists of characters and doubles. So when you read in a number you probably need to convert it to a double.

Also be wary of while (!infile.eof()) it has known problems and is best avoided unless you what you are doing.

Also when you are comparing characters don't forget the single quote mark around it. For example:-

``else if (character == m)``

becomes:-

``else if (character == 'm')``

Like iamthwee already said, using eof() as a loop condition for reading file usually doesn't work, because eof() evaluates as true after the read is unsuccessful. Here's a more in-depth explanation and the alternative:
http://www.gidnetwork.com/b-58.html (note: eof() == feof() )

And you can throw out `char f, m` , because of course, you're going to be comparing the actual characters (using single `'` s), not the variables.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.