copy objec from file to array or vector

Hi all!

I have a file containing information of person like:

name(string) age(int) gender(char) .....

as an object attribute like let say perobj as an object from Person class.

know i want to know how to create an array of Person class let say Person myperson[] and copy all objects from file to array.


ps:vector or list is OK also!

thanks
Could you give an example of one of the "objects" in the file?
wow fast reply!

file looks like this!
data.txt:

Jack 23 M
Maggy 40 F

so i want to copy this data in an array like Person per[]

so i can use statement like this

per[0].getneme() or something like per[1].setname("Mary") and so on...

I just noticed that i want to rewrite the edited information in the same file!!!!

wow fast reply!
You were lucky. Weekends are slow.

Are you expecting to have spaces in the name, or will the name always be exactly one word?
let it be one word!
Why don't you overload the >> operator to get data into your class?
you mean something like this?

1
2
3
4
5
6
7
8
9
Person perobj[];//how to find the number of objects?, it should be the number of line in the file
int i=0;

while(!data.eof()){

data>>perobj[i].setname()>>perobj[i].setage()>>perobj[i].setgender();
i++;
//here is one of my problems! don't know how to go to the next line
}
Last edited on
Not really.
In your class:
1
2
3
4
5
6
class Person
{
    // some members ...

   friend std::istream &operator >> ( std::istream &, Person & ); // so that >> can access private members
};
operator >> implementation:
1
2
3
4
5
std::istream &operator >> ( std::istream &is, Person &pers)
{
    is >> pers.name >> pers.age >> pers.gender; // use directly member variables, not setter functions
   return is;
}

While reading -let's say you have a list-:
1
2
3
Person temp; // declare temporary Person object
data >> temp; // read it from the file
person_list.push_back ( temp ); // add it to the list - this way data could contain any number of people 
brilliant solution!!

and i can do same thing for copying in file with overloading << operator hmmm..!

but why you use class private members directly instead of using setter functions? does it have any reason or its just good programming habit!
It is faster:
with friend:
1
2
3
4
operator >> etc
{
    is >> pers.member;
}

without friend:
1
2
3
4
5
6
operator >> etc
{
    type temp;
    is >> temp;
    pers.set_member ( temp );
}
Thanks so much dude!
Topic archived. No new replies allowed.