0

I'm writing a small class Student. My goal is to write the data of an object of the class to a txt file, then read all lines in the file and create the appropriate number of objects from the same file.

These are the private data members

class Student {
char* m_name = new char[1000];
int m_number;
double m_grade;

The getters:

char* getName () const {return m_name;}
int getNum () const {return m_number;}
double getGrade () const {return m_grade;}

Operator >>:

ostream& operator<< (ostream& ost, const Student& obj){
    ost << obj.m_name << endl << obj.m_number << endl << obj.m_grade << endl;
    }

(the info in the txt files for 2 objects looks like this)

John Doe
12345
5.67
Jane Doe
98765
66666
4.44

Operator >> (I really need suggestions how to overload it better. I don't like how I've done it. Also is it possible to overload it using "const Student& obj" as second argument?)

   istream& operator>> (istream& ist, Student& obj){
    char* temp = new char[255];
    int tempNum = 0;
    double tempGrade = 0;
    ist.getline(temp, 255);
    obj.setName(temp);
    ist >> tempNum;
    ist >> tempGrade;
    obj.setNum(tempNum);
    obj.setGrade(tempGrade);
    }

And finally my load function: (It doesn't work, runtime (array boundaries) error)

 vector<Student> load () {
    ifstream ifs ("Data.txt");
    while (ifs){
        Student temp;
        ifs >> temp;
        cout << temp << endl;
        load.push_back(temp);
    }

I really would appreciate any suggestions on how to make the load function work using my ">>" operator and also how to overload ">>" better

NathanOliver
  • 150,499
  • 26
  • 240
  • 331
Play4u
  • 87
  • 6
  • in the code you are using the `<> operator – RazaUsman_k Aug 24 '17 at 12:58
  • `const` doesn't make much sense on a parameter you intend to modify. You consistently forget the return value. (Your compiler should warn you about this.) You should read [Why is `iostream::eof` inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). Use `std::string`, not `char*`. – molbdnilo Aug 24 '17 at 12:58
  • @molbdnilo I don't think I've forgotten the return value apart from load(), which is not finished yet. Thanks for the read on iostream::eof. Since I'm doing a project for school, we are not allowed to use std::string. Only char* – Play4u Aug 24 '17 at 13:02
  • Yes you do forget return values. Your `ostream& operator<>(...)` – Igor Tandetnik Aug 24 '17 at 13:10
  • @IgorTandetnik Yes, you are right! Didn't quite catch that. Thank you – Play4u Aug 24 '17 at 13:12

0 Answers0