In: Computer Science
c++
students.txt
20
Shawn Lynch 2.0 Hasan Stephens 2.6 Frank Wright 2.7 Hugo Ray 2.9 Justin Gardner 3.0 Kelly Jenkins 2.2 Rafael Seymour 3.7 Jose Cantu 0.6 David Gilmore 1.3 Emma Paterson 2.1 Jackie White 1.9 Robert Green 3.8 Julio Armstrong 1.1 Erik Cook 4.0 Jessica Hale 3.0 Vanessa Rivera 0.9 Sandra Ferguson 3.1 Christian Wang 1.1 Jackson Martinez 1.9 Austin Black 4.0
For your program, you will need to define a class Student, with private members for first name, last name, and GPA, and any methods you determine that you need (constructors, gets/sets, etc.) Once the class is defined, you will need to populate an array of Student objects to be sorted with data provided in the students.txt file.
First line in the text file will be size of the array.
Every line after the first contains three pieces of information, separated by spaces: First Name, Last Name, and GPA
and sort the Student data by GPA.(Using MergeSort)
display unsorted data and sorted data
Description:
Program:
#include<iostream>
#include<fstream>
#include<vector>
#include<string>
using namespace std;
Class Student{
private:
string firstName, lastName;
int GPA;
public:
//setter functions
void setFirstName(string firstName)
{
this.firstName = firstName;
}
void setLastName(string setLastName)
{
this.lastName = lastName;
}
void setGPA(int GPA)
{
this.GPA = GPA;
}
//getter functions
string getFirstName()
{
return this.firstName;
}
string getLastName()
{
return this.lastName;
}
string getGPA()
{
return this.GPA;
}
}
bool sortByGPA(Student &A, Student &B)
{
return(A.GPA < B.GPA);
}
// main Driver method
int main()
{
ifstream fin;
vector<string> vec;
fin.open(students.txt);
//read first line from .txt file to find the size of array.
getline(fin,line);
//stoi(string) returns the integer value of a string.
int sizeOfArray = stoi(line);
Students st[sizeOfArray];
int i=0;
while (fin) {
// Read a Line from File
getline(fin, line);
// After segregating the data from line we are storing it in a vector
string word = " ";
for (int CURRENT = 0; CURRENT < line.length();
CURRENT++)
{
if (line[CURRENT] == ' ')
{
vec.push_back(word)
word = "";
}
else
{
word += line[CURRENT];
}
}
vec.push_back(word);
// assign the data of vector to object of student and free the vector for next student
st[i].setFirstName(vec[0]);
st[i].setLastName(vec[1]);
st[i].setGPA((stoi(vec[2]));
i++;
vec.clear();
}
// Close the file
fin.close();
//sort the student object with respect to GPA
st.sort(sortByGPA);
return 0;
}