See if you like this sort of a setup. There are a few minor things to improve, there is a lot to play with:
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void get_student_grades(ifstream&, int*);
int calc_total_score(const int*, const int);
char calc_grade(int avg);
void save_record(ofstream& file, string name,int* arr, int size, int avg);
int main ()
{
string StudentName;
//Always initialize arrays when possible: prevents weird behaviour. int Grades[5] = {0};
int TotalScore(0);
int AverageScore(0);
//--
ifstream StudentDB("students.txt");
//Could the file be opened without any errors? if(!StudentDB)
{
cout<<"Couldn't open file (correctly). Exiting application..."<<endl;
return(1);
}
//Let's create a file to store formatted data.
ofstream FmtDB("grades.txt");
//Setup the header of the formatted data on a different file.
FmtDB << "Name\tScore 1\tScore 2\tScore 3\tScore 4\tScore 5\tAverage\tFinal\t"<<endl;
//-- while(StudentDB >> StudentName)
{
//First, let's collect data.
get_student_grades(StudentDB, Grades);
TotalScore = calc_total_score(Grades, 5);
AverageScore = TotalScore/5;
//Second, we store the record on already prepared file.
save_record(FmtDB, StudentName, Grades, 5, AverageScore);
}
//-- return 0;
}
//------------------------------------- void get_student_grades(ifstream& dbase, int* arr)
{
unsigned i(0);
while(dbase >> arr[i])
{
++i;
}
//Give database file back in a decent state.
dbase.clear();
}
//------------------------------------- int calc_total_score(const int* arr, const int size)
{
int total(0);
for(int i = 0; i < size; ++i)
{
total += arr[i];
}
return total;
}
//------------------------------------- char calc_grade(int avg)
{
if (avg >= 90)
return 'A';
if (avg >= 80)
return 'B';
if (avg >= 70)
return 'C';
if (avg >= 60)
return 'D';
//Bad student: score lower then 60. return 'F';
}
//------------------------------------- void save_record(ofstream& file, string name, int* arr, int size, int avg)
{
file << name <<"\t";
for(int i = 0; i < size; ++i)
{
file << arr[i] << "\t";
}
file << avg << "\t";
file << calc_grade(avg) <<endl;
}