Given the Student struct:
struct Student{
string fName;
string lName;
int age;
float gpa;
float scores[NUM];//English, Mathematics, Biology
};
FirstName LastName Age Gpa
EnglishScore MathScore BiologyScore
float AvgEnglish(Student s[], int numberOfStudents);
string BestStudentBiology(Student s[], int numberOfStudents);
C++ code for above problem
#include<iostream>
#include<fstream>
#define MAX 20
#define NUM 3
using namespace std;
struct Student
{
string fName;
string lName;
int age;
float gpa;
float scores[NUM];
};
// function that reads data from file and returns number of
lines read from file
int read_data(Student s[])
{
int len=0;
ifstream myfile("Test.txt");
if(myfile.is_open())
{
string line;
while(getline(myfile,line))
{
len++;
}
myfile.close();
ifstream file("Test.txt");
for(int i=0;i<len;i++)
{
file >>
s[i].fName;
file >>
s[i].lName;
file >>
s[i].age;
file >>
s[i].gpa;
for(int
j=0;j<NUM;j++)
{
file >> s[i].scores[j];
}
}
file.close();
}
return len;
}
// function that retuns the average marks in English
subject
float AvgEnglish(Student s[], int numberOfStudents)
{
if(numberOfStudents==0)
return 0.0;
float sum=0.0;
for(int i=0;i<numberOfStudents;i++)
{
sum+=s[i].scores[0];
}
return sum/numberOfStudents;
}
// function that returns the Name of Best Student in Biology
subject
string BestStudentBiology(Student s[], int numberOfStudents)
{
if(numberOfStudents==0)
return "";
int max_index=0;
for(int i=1;i<numberOfStudents;i++)
{
if(s[max_index].scores[2]<s[i].scores[2])
{
max_index=i;
}
}
return s[max_index].fName+"
"+s[max_index].lName;
}
// testing main function
int main()
{
struct Student students[MAX];
int len=read_data(students);
cout << "Average marks in English: " <<
AvgEnglish(students,len) << endl;
cout << "Best Student in Biology: " <<
BestStudentBiology(students,len) << endl;
return 0;
}
Sample output
if "Test.txt" has following data
Captain America 25 8.5 67 78 8
Iron Man 24 9.3 45 63 56
Black Panther 23 7.7 65 72 88
Doctor Strange 27 6.9 45 47 65
Ant Man 25 6.6 77 54 58
Spider Man 22 7.3 44 76 85
Captain Marvel 21 8.8 65 66 67
then after running the above code, output looks as follows:
Mention in comments if any mistakes or errors are found. Thank you.
Get Answers For Free
Most questions answered within 1 hours.