1

I have the following Repository class and I want the initial vector students to be built from a text file. The objects are of type {string, int, int} and I'm thinking about using new line as delimiter between objects. Is it be possible to make the private vector be constructed/initialized from file?

Here is the header of my Repository class:

class StudentRepository{
private:
    vector <Student> students;
public:
    vector <Student> getAll();

    ~StudentRepository();
};

P.S.: any advice regarding my question or link to a useful tutorial are welcome.

Edit:
This is were i got but i`m having issues with the loading of the objects because they look like this, how couldi delimit the string from ints?:

Foo bar 100 23
Bar Foo 101 42

Code:

void StudentRepository::loadStudents(){
ifstream fl;
fl.open("studs.txt");
Student A();
if(fl.is_open()){
    while(!(fl.eof())){
        getline(A.);/// i connot manage to delimite parts of the line.
    }
}
else{
    cout<<"~~~ File couldn't be open! ~~~"<<endl;
}
}

void StudentRepository::saveStudents(){
    ofstream fl;
    fl.open("studs.txt");
    if(fl.is_open()){
        for(int i=0; i<students.size(); i++){
            fl<<students[i];
        }
    }
    else{
        cout<<"~~~ File couldn't be open! ~~~"<<endl;
    }
}
Mike
  • 47,263
  • 29
  • 113
  • 177
Bogdan M.
  • 2,161
  • 6
  • 31
  • 53
  • 8
    It's definitely possible. What have you tried so far? – David B May 24 '12 at 13:34
  • i'm trying to make a inner function in teh repository and it is under construction, i wanted to make sure. :) thank you. – Bogdan M. May 24 '12 at 13:41
  • Just post the code for the attempts that you have tried so far (if any). – betabandido May 24 '12 at 13:44
  • 1
    A very similar question earlier today [here](http://stackoverflow.com/questions/10735217/inputting-a-file-into-a-structure/10735566#comment13946861_10735566). – acraig5075 May 24 '12 at 13:49
  • 2
    I would've created a Loader class which parses the file given to it and has a method which returns student objects which you then use to populate the vector. So something like: while(student = loader.get_next_student()) student_repository.add_student(student); The answer above shows you how to parse the file. – jaho May 24 '12 at 14:00
  • i am not doing a new class but creating a 2 new functions saveStudents() & loadStudents(); – Bogdan M. May 24 '12 at 14:04
  • 1
    @user1388172 You can use the same approach in its own function, what Marian is suggesting gives a better OO method (more abstraction). If you're going to be populating vectors a lot, then having it in its own class makes sense. – David B May 24 '12 at 14:11
  • There is how far i go but i encoutered a new problem how can i read and build the objects from "abc xys 111 2222" to {string,int,int} – Bogdan M. May 24 '12 at 14:14

0 Answers0