-4

If I have a file containing 10 rows, where each row contain information about the following object,

class student
{
    public:
    string name;
    int age;
    int rollnum;
    int year;
    string father;
    string mother;
    string category;
    string region;
    char sex;
    string branch;
    int semester;
};

How can I read all the 10 objects information from a file? ( I am guessing I will have to take an array of 10 objects for this )

  • Overload `operator>>`. – chris Aug 30 '14 at 14:27
  • There's a [particularly nice, well-named question](http://stackoverflow.com/questions/4421706/operator-overloading) on the site. – chris Aug 30 '14 at 14:31
  • https://www.google.com/search?q=overload+insertion+and+extraction+operator+in+c%2B%2B&oq=overload+extraction – Ryan Haining Aug 30 '14 at 14:31
  • also depends a bit what you mean by "file" as the method for a `FILE *` and an `ifstream` will be different. – Ryan Haining Aug 30 '14 at 14:33
  • Class with all public members, might as well be a struct. – Borgleader Aug 30 '14 at 14:33
  • possible duplicate of [Why does reading a struct record fields from std::istream fail, and how can I fix it?](http://stackoverflow.com/questions/23047052/why-does-reading-a-struct-record-fields-from-stdistream-fail-and-how-can-i-fi) – πάντα ῥεῖ Aug 30 '14 at 16:03
  • It might be worth looking at Google's protocol buffers: https://developers.google.com/protocol-buffers/. They handle versioning (e.g. if you decide to change your object in the future, older versions will still read the file...) and you don't need to worry about writing the serializing (saving)/deserializing (loading) code. – jonathanverner Sep 01 '14 at 09:18

1 Answers1

0
istream& operator >>(istream& in, student& val) {
    return in >> name >> age >> rollnum >> year; // ...
}

Then you can do this:

for (string line; getline(infile, line); ) {
    istringstream stream(line);
    student person;
    stream >> person;
}

Now person is being populated once per line. I do it this way rather than directly streaming from the file because this way is safer: if a line has the wrong number of tokens it won't misunderstand what the columns are, whereas without getline() you might naively parse 10 tokens of an 11 token line, then think that the 11th token on the line is the first token of the next record. Just a typical mistake that happens in beginner C++ text parsing code.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436