File input and output turn in the program listing and the output file. All progr
ID: 3559964 • Letter: F
Question
File input and output turn in the program listing and the output file. All programs should include comment headers and comments throughout the code where necessary. Complete the following program and execute using the input file:
#include
#include
using namespace std;
int main() {
const char* INFILE = "a:\grades.dat";
const char* OUTFILE = "a:\grades.out";
int grades, total, count;
float average;
grades = 0;
total = 0;
count = 0;
average = 0.0f;
ifstream inGrades;
inGrades.open (INFILE);
if ( !inGrades ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}
ofstream outGrades;
outGrades.open (OUTFILE);
while ( inGrades >> grades ) {
outGrades << grades << endl;
total += grades;
count ++;
}
inGrades.close();
average = static_cast (total) / static_cast (count);
outGrades << "Your average grade is " << average << endl;
outGrades <<"and your letter grade is ";
// Complete the program by adding a multi-way selection that
// prints the letter grade to the output file.
outGrades << endl;
outGrades.close();
cout << "Program is finished running!" << endl; return 0; }
The input file for your program: grades.dat 90 80 100 75 83
Explanation / Answer
#include <iostream>
#include <fstream>
using namespace std;
int main() {
const char* INFILE = "a:\grades.dat";
const char* OUTFILE = "a:\grades.out";
int grades, total, count;
float average;
grades = 0;
total = 0;
count = 0;
average = 0.0f;
ifstream inGrades;
inGrades.open (INFILE); // open file
if ( !inGrades ) { // check if file exists or not.
cerr << "File could not be opened." << endl;
exit( 1 );
}
ofstream outGrades;
outGrades.open (OUTFILE); // open output file..
while ( inGrades >> grades ) {
outGrades << grades << endl;
total += grades;
count ++;
}
inGrades.close(); // close input file.
average = static_cast <float> (total) / static_cast <float> (count);
outGrades << "Your average grade is " << average << endl; // write average to file
outGrades <<"and your letter grade is ";
// Complete the program by adding a multi-way selection that
// prints the letter grade to the output file.
if(average >90 && average<=100)
outGrades <<" A " ;
else if(average >80 && average<=90)
outGrades <<" B " ;
else if(average >70 && average<=80)
outGrades <<" C " ;
else if(average >60 && average<=70)
outGrades <<" D " ;
else
outGrades <<" F " ;
outGrades << endl;
outGrades.close();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.