Bogdan M.
Bogdan M.

Reputation: 2191

Implementing in the Constructor a function

I'm trying to read from a file some data I already have and to load it into a vector. Then I'm trying to save the changes to file (which works).

But when I run the program, it doesn't read my file. Here is my code:

Save / Load Functions:

void StudentRepository::loadStudents(){
    ifstream fl;
    fl.open("studs.txt");
    Student st("",0,0);
    string str,ss;
    int i;
    int loc;
    if(fl.is_open()){
        while(!(fl.eof())){
            getline(fl,str);
            loc = str.find(",");
            ss = str.substr(0,loc);
            st.setName(ss);
            str.erase(0,loc);
            loc = str.find(",");
            ss = str.substr(0,loc);
            i = atoi(ss.c_str());
            st.setId(i);
            str.erase(0,loc);
            i = atoi(ss.c_str());
            st.setGroup(i);

        }
    }
    else{
        cout<<"~~~ File couldn't be open! ~~~"<<endl;
    }
    fl.close();
}


void StudentRepository::saveStudents(){
    ofstream fl;
    fl.open("studs.txt");
    if(fl.is_open()){
        for(unsigned i=0; i<students.size(); i++){
            fl<<students[i].getName();
            fl<<",";
            fl<<students[i].getID();
            fl<<",";
            fl<<students[i].getGroup();
            fl<<endl;
        }
    }
    else{
        cout<<"~~~ File couldn't be open! ~~~"<<endl;
    }
}

Implementation (as far I could go) - I called the load function as the vector in the memory was created:

StudentRepository::StudentRepository(){
loadStudents();
}

Any ideas what/where I did something wrong, or some advice to fix it?

Upvotes: 0

Views: 87

Answers (1)

melmi
melmi

Reputation: 1008

It seems that you read student info correctly. But you do not add read info into any vector. You should have something like students.push_back(st); in your loadStudents method. Furthermore it is better idea to initialize st at the beginning of the loop.

Upvotes: 1

Related Questions