/*********************************************
This program reads in student/grade data from
namedgrades.txt, gets a name from the user and
prints out his homework average.
**********************************************/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
/*********************************************
** PROTOTYPES & STRUCT DEFINITIONS
*********************************************/
struct Student
{
int *hw;
string name;
};
int find(string name, Student *A, int N);
double average(int *A, int N);
/*********************************************
** MAIN FUNCTION
*********************************************/
int main()
{
// Open file and read header info
int Ns, Nh;
string junk;
ifstream IN("namedgrades.txt");
IN >> Ns >> junk >> Nh >> junk;
// Create array of Ns students with Nh grades each
Student *stu = new Student[Ns];
for(int j = 0; j < Ns; j++)
stu[j].hw = new int[Nh];
// Read & store student names & grades
for(int i = 0; i < Ns; i++)
{
IN >> stu[i].name;
for(int j = 0; j < Nh; j++)
IN >> stu[i].hw[j];
}
// Get name from user
string name;
cout << "Enter name: ";
cin >> name;
// Find student with given name & print his average
int k = find(name,stu,Ns);
cout << "Average is: " << average(stu[k].hw,Nh) << endl;
return 0;
}
/*********************************************
** FUNCTION DEFINITIONS
*********************************************/
// Returns index of array element whose name
// data member matches given name.
int find(string name, Student *A, int N)
{
int k = 0;
while(name != A[k].name)
k++;
return k;
}
// Returns the average of the N ints in array A
double average(int *A, int N)
{
int sum = 0;
for(int i = 0; i < N; i++)
sum = sum + A[i];
return double(sum)/N;
}