I need to read class objects from file, but I don't know how.
Here I have a class "People"
class People{
public:
string name;
string surname;
int years;
private:
People(string a, string b, int c):
name(a),surname(b),years(c){}
};
Now I would like to read peoples from .txt file and store them to objects of a class People.
For instance, this is how my .txt file looks like:
John Snow 32
Arya Stark 19
Hodor Hodor 55
Ned Stark 00
I think the best way to do this would be to create array of 4 objects. I need to read word by word and line after line, if I assume correctly but I don't know how...
The way to do this would be to compose a storage format for your class, for instance if I were to do this I would store the information just like you did
John Snow 32
Arya Stark 19
Hodor Hodor 55
Ned Stark 00
To read this in you could do the following
ifstream fin;
fin.open("input.txt");
if (!fin) {
cerr << "Error in opening the file" << endl;
return 1; // if this is main
}
vector<People> people;
People temp;
while (fin >> temp.name >> temp.surname >> temp.years) {
people.push_back(temp);
}
// now print the information you read in
for (const auto& person : people) {
cout << person.name << ' ' << person.surname << ' ' << person.years << endl;
}
To write it to a file you could do the following
static const char* const FILENAME_PEOPLE = "people.txt";
ofstream fout;
fout.open(FILENAME_PEOPLE); // be sure that the argument is a c string
if (!fout) {
cerr << "Error in opening the output file" << endl;
// again only if this is main, chain return codes or throw an exception otherwise
return 1;
}
// form the vector of people here ...
// ..
// ..
for (const auto& person : people) {
fout << people.name << ' ' << people.surname << ' ' << people.years << '\n';
}
If you are not familiar with what a vector
is vector
s are the recommended way to store an array of objects that can grow dynamically in C++. The vector
class is a part of the C++ standard library. And since you are reading in from a file you should not make any assumptions about how many objects are going to be stored in the file ahead of time.
But just in case you are not familiar with the classes and features I used in the example above. Here are some links
vector http://en.cppreference.com/w/cpp/container/vector
ifstream http://en.cppreference.com/w/cpp/io/basic_ifstream
range based for loop http://en.cppreference.com/w/cpp/language/range-for