Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ Class Serialization
    text
    copied!<p>I quite recently learned about the C++ classes friend keyword and the uses in serialization and now I need some help in getting it to work.</p> <p>I have no problem serializing my class to a file, it's working great, however i'm having a hard time trying to read this file into a vector container. I'm sure I need a loop in my code that reads line by line, but since the class has different types I guess I can't use std::getline() and also maybe that approach wouldn't use the istream method i implemented? A sample output file would be:</p> <pre><code>Person 1 2009 1 Person 2 2001 0 </code></pre> <p>My code:</p> <pre><code>class SalesPeople { friend ostream &amp;operator&lt;&lt;(ostream &amp;stream, SalesPeople salesppl); friend istream &amp;operator&gt;&gt;(istream &amp;stream, SalesPeople &amp;salesppl); private: string fullname; int employeeID; int startYear; bool status; }; ostream &amp;operator&lt;&lt;(ostream &amp;stream, SalesPeople salesppl) { stream &lt;&lt; salesppl.fullname &lt;&lt; endl; stream &lt;&lt; salesppl.startYear &lt;&lt; endl; stream &lt;&lt; salesppl.status &lt;&lt; endl; stream &lt;&lt; endl; return stream; } istream &amp;operator&gt;&gt;(istream &amp;stream, SalesPeople &amp;salesppl) { stream &gt;&gt; salesppl.fullname; stream &gt;&gt; salesppl.startYear; stream &gt;&gt; salesppl.status; // not sure how to read that empty extra line here ? return stream; } // need some help here trying to read the file into a vector&lt;SalesPeople&gt; SalesPeople employee; vector&lt;SalesPeople&gt; employees; ifstream read("employees.dat", ios::in); if (!read) { cerr &lt;&lt; "Unable to open input file.\n"; return 1; } // i am pretty sure i need a loop here and should go line by line // to read all the records, however the class has different // types and im not sure how to use the istream method here. read &gt;&gt; employee; employees.push_back(employee); </code></pre> <p>By the way, I know that the Boost library has a great serialization class, however I'm trying to learn how serialization would work using the STL library for now. Thanks a lot in advance for any help that you can give me and for getting me in the right track!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload