struggling with output to a file



void calcScore(ofstream& fout, string name, double score1, double score2, double score3, double score4, double score5)
{
double lowest, highest;
highest = findHighest( score1, score2, score3, score4, score5);
lowest = findLowest(score1, score2, score3, score4, score5);



double totalScore = (score1 + score2 + score3 + score4 + score5)-(highest+lowest);
double avgScore = (totalScore)/3;

fout.open("results.dat");
fout << setprecision (3);
fout << name << " " << avgScore << endl;
fout.close();
}
[/code]

Basically, I need the name from the input file (which looks like this:)
1
2
3
2
Jennifer 10 9 8 9.5 10
Michael 10 9 10 9 10


and the average of the scores omitting the highest and lowest score. I have been getting it to output one of the names and averages with the code the way that it is, but am having no luck getting it to preform correctly.

What should I do in order to fix this file output problem? The data is reading into the program from a file just fine, but will not write out to a different one correctly.
Last edited on
Bravo for a good try.

The problem is on line 125. When you're opening the file, you're overwriting your old file (a.k.a. "truncating"). I can think of two ways to solve this.

1) Open the file once, pass the stream around to the functions that need it, and in the end, close the stream.

2) change line 125 to open the stream in "append mode" (see http://www.cplusplus.com/reference/iostream/ofstream/open/ for details).

Hope this helps.

EDIT: Note: option 2 has a side effect. Run your program more than once and it will continue to add data to the same file.
Last edited on
Thanks so much! That made it work perfectly
Topic archived. No new replies allowed.