#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
usingnamespace std;
class Course {
public:
string get_name() const {
return name;
}
int get_students() const {
return students;
}
virtualvoid read(ifstream& infile) {
infile >> name >> students;
}
protected:
string name;
int students;
};
class Lecture : public Course {
public:
int get_num() {
return num;
}
virtualvoid read(ifstream& infile) {
Course::read(infile);
infile >> num;
}
void write(ostream& outfile) {
outfile << get_name() << " " << get_students() << " " << num
<< "\n";
}
private:
int num;
};
int main()
{
vector <Lecture* > lec;
int lec_count = 0;
string lecCourse;
cout << "First file: " << "\n";
cin >> lecCourse;
ifstream inf;
inf.open(lecCourse.c_str());
if (inf.fail()) {
cout << "No such file - First file" << "\n";
return 1;
}
else {
int temp;
inf >> temp;
for (int i = 0; i < temp; i++) {
lec[lec_count] = new Lecture();
lec[lec_count]->read(inf);
lec.push_back(new Lecture());
lec_count++;
}
inf.close();
}
for (int i = 0; i < lec_count; i++) {
lec[i]->write(cout);
}
string exit;
cout << "Exit file: " << "\n";
cin >> exit;
ofstream output;
output.open(exit.c_str());
if (output.fail()) {
cout << "No such file - Third file" << "\n";
return 1;
}
else {
for (int i = 0; i < lec_count; i++)
{
lec[i]->write(output);
}
output.close();
}
}
Example of my input file:
3
test1 11 12
test2 22 23
test3 33 34
3 - number of lines to read
test1 - name (Course)
11 - students(Course)
12 - num(Lecture)
Basically one string and two ints, in that order.
So i am trying to read the file above and write it down into the vector lec. I'm doing so using the functions read and write in my classes, as shown above.
I am not reviecing any error, but nothing is being written to my output file. I am 99% sure my mistake is in the for loop where i try to read the content of the file and write it down to the vector, but I just can't figure it out. Any advice?
for (int i = 0; i < temp; i++) {
lec[lec_count] = new Lecture(); //at this point `lec' is empty, so an invalid access
lec[lec_count]->read(inf);
lec.push_back(new Lecture()); //and here you add an empty object
lec_count++;
}
> vector <Lecture* > lec;
If all your objects are going to be of class `Lecture' you may simply write vector<Lecture> lec;
If the idea is to observe polymorphism, then perhaps they wanted a vector<Course*>
as you are using new to allocate the objects, don't forget to delete them
(may use a smart pointer for that)
Since you completely ignored my question about your class design in your previous thread, I'll try again here:
Why do you have Lecture inheriting from Course? Do you understand that inheritance should model an "is-a" relationship? Do you understand that it is not true that a lecture is a course?
I'd suggest re-thinking your design, and the relationship between your classes.