For the following c++ code there is an extra row that is added to my output file
ID: 662895 • Letter: F
Question
For the following c++ code there is an extra row that is added to my output file. Please fix.
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
void avg_grade(ifstream& infile, ofstream& outfile);
int main()
{
ifstream infile;
ofstream outfile;
avg_grade(infile,outfile);
return 0;
}
void avg_grade(ifstream& infile, ofstream& outfile)
{
infile.open("grades.txt");
if(infile.fail())
{
cout<<"File not found "<<endl;
}
outfile.open("grades_result.txt");
if(outfile.fail())
{
cout<<"File not found "<<endl;
}
while(!infile.eof())
{
double average;
double total =0, i;
char last_name,first_name;
for (int x = 0; x < 2; x++)
{
string s;
infile>>s;
outfile<< s << " ";
}
for(i=0; i<10; i++)
{
double subject;
infile>>subject;
outfile<<subject<<" ";
total=total+subject;
}
average=total/10;
outfile<<average<<endl;
}
return;
}
Explanation / Answer
#include <bits/stdc++.h>
using namespace std;
void avg_grade(ifstream& infile, ofstream& outfile);
int main() {
ifstream infile;
ofstream outfile;
avg_grade(infile,outfile);
return 0;
}
void avg_grade(ifstream& infile, ofstream& outfile) {
infile.open("grades.txt");
if(infile.fail()) {
cout<<"File not found "<<endl;
}
outfile.open("grades_result.txt");
if(outfile.fail()) {
cout<<"File not found "<<endl;
}
string out;
while(!infile.eof()) {
double average;
double total =0, i;
char last_name,first_name;
for (int x = 0; x < 2; x++) {
string s;
infile>>s;
out = out + s + " ";
}
for(i=0; i<10; i++) {
double subject;
infile>>subject;
ostringstream strs;
strs << subject;
string str = strs.str();
out = out + str + " ";
total=total+subject;
}
average=total/10;
ostringstream strs;
strs << average;
string str = strs.str();
out = out + str +" ";
}
out = out.substr(0,out.length()-1);
outfile << out;
return;
}