Implement a C++ class called Student which has a name, a major and a vector of c
ID: 3873045 • Letter: I
Question
Implement a C++ class called Student which has a name, a major and a vector of courses. The course class has a name and a semester in which it was taken. The constructor of the student class will read a text file that contains information for one student and many courses such as: Ahmad Awad Finance CMP 120 Fall 2012 CMP 220 Spring 2013 CMP 305 Summer 2013 You are also asked to create a destructor for the student class that writes all information back to an output.txt file. Note that all member variables must be private.Explanation / Answer
#include<iostream>
#include<fstream>
#include<vector>
#include<string>
using namespace std;
class course{
private:
string name;
string timeOfSemester;
public:
course(string nm, string tm){
name = nm;
timeOfSemester = tm;
}
string getName(){
return name;
}
string getTimeOfSemester(){
return timeOfSemester;
}
};
class Student {
private:
string name;
string major;
vector<course> study;
public:
Student(string nm){
string line,line2;
ifstream fin(nm.c_str());
if (!fin){
cout << "Error opening file ";
}
else {
int count = 0;
while(getline(fin,line)){
if (count == 0){
name = line;
}
if (count == 1){
major = line;
}
if (count > 1){
if (getline(fin,line2)){
course cr(line,line2);
study.push_back(cr);
}
}
count++;
}
}
}
void display(){
cout << name << endl;
cout << major << endl;
for (int i = 0; i<study.size(); i++){
cout << study[i].getName() << endl;
cout << study[i].getTimeOfSemester() << endl;
}
}
~Student(){
ofstream fout("output.txt");
fout << name << endl;
fout << major << endl;
for (int i = 0; i<study.size(); i++){
fout << study[i].getName() << endl;
fout << study[i].getTimeOfSemester() << endl;
}
fout.close();
}
};
int main(){
Student st("input32.txt");
st.display();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.