Possible Duplicate:
enhancing a program – complete failure
im asked to write a program to read the content of a text file in the form of:
Jones Tom 94 99 96 74 56 33 65 89 87 85
Thompson Frank 67 58 86 95 47 86 79 64 76 45
Jackson Tom 95 97 94 87 67 84 99 45 99 87
Jackson Michael 43 23 34 77 64 35 89 56 75 85
Johnson Sara 84 93 64 57 89 99 74 64 75 35 91
and output the average of each student into another file in the form of:
Jones Tom 94 99 96 74 56 33 65 89 87 85 77.8
Thompson Frank 67 58 86 95 47 86 79 64 76 45 70.3
Jackson Tom 95 97 94 87 67 84 99 45 99 87 85.4
Jackson Michael 43 23 34 77 64 35 89 56 75 85 58.1
Johnson Sara 84 93 64 57 89 99 74 64 75 35 73.4
i successfully managed to do that using the code below:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
using namespace std;
int main()
{
fstream infile("grades.txt",ios::in);
if(!infile){cerr<<"file could not be found!";exit(1);}
fstream outfile("average.txt",ios::out);
if(!outfile){cerr<<"file could not be created!";exit(1);}
char fname[20];
char lname[20];
int grades;
char c;
int lines=1;
double avg=0;
while(infile.get(c))
{if(c=='\n') lines++;}
infile.clear();
infile.seekg(0);
for(int k=0;k<lines;k++)
{
infile>>fname;
infile>>lname;
outfile<<fname<<" "<<lname<<" ";
int sum=0;
for(int i=0;i<10;i++)
{
if(infile>>grades)
{sum+=grades;
outfile<<grades<<" ";}
}
outfile<<(double)sum/10.0<<endl;
}
system("pause");
return 0;
}
but i have a problem.
when the first line of the text file contains grades less than 10. for example:
Jones Tom 94 99 96 74 56 33 65 89 87
i get a messed up output, which is ruining everything. im getting the output below:
Jones Tom 94 99 96 74 56 33 65 89 87 69.3
0
0
0
0
How can i fix this problem? and how can i make the program to output zeros if i have less than ten grades on each line?
so that for example if i have on the first line:
Jones Tom 94 99 96 74 56 33 65 89
i want the program to calculate the average and output the following to the other file.
Jones Tom 94 99 96 74 56 33 65 89 0 0 64.3
note that 64.3 is the average of the student.
thank you.
kind regards.
Well, the solution is really simple. First, separate the code into two parts, the first to read the grades, do the averaging and write the grades to the output file and the second to write the zeros and the average.
Have the part that reads the scores accumulate them in
sum. Now, you can use the sum and the counter to compute the average.Let us look at how the code to read the scores would work
Finally, in the second part writing to the output file, you’ll want to do something like this:
Now, the above pseudo-code isn’t very good since it doesn’t have checks and such. You’ll want to ensure you haven’t read in more than 10 grades for instance.
Since you had trouble with the condition in the first part, here’s a bit of code to help:
I hope this helps out.