// ========================================================================== // $Id: person_io.cpp,v 1.3 2014/11/29 00:31:44 jlang Exp $ // CSI2372 example Code for lecture 8 // ========================================================================== // (C)opyright: // // Jochen Lang // SITE, University of Ottawa // 800 King Edward Ave. // Ottawa, On., K1N 6N5 // Canada. // http://www.site.uottawa.ca // // Creator: jlang (Jochen Lang) // Email: jlang@site.uottawa.ca // ========================================================================== // $Log: person_io.cpp,v $ // Revision 1.3 2014/11/29 00:31:44 jlang // Check-in of in-class version // // Revision 1.2 2011/09/10 01:08:19 jlang // Updates F10 // // Revision 1.1 2006/10/17 22:18:48 jlang // Added examples for lecture 8 // // // ========================================================================== #include #include #include // rand() requires #include using namespace std; class Person; istream& operator>>( istream&, Person&); ostream& operator<<( ostream&, const Person& ); class Person { string d_lastName; string d_firstName; int d_sin; public: Person( const string& _firstName = "", const string& _lastName = "" ); ~Person() { cout << "~Person: " << d_lastName << endl; } friend istream& operator>>( istream&, Person& ); friend ostream& operator<<( ostream&, const Person& ); }; Person::Person( const string& _firstName, const string& _lastName ) : d_firstName( _firstName ), d_lastName( _lastName ), d_sin( 0 ) { d_sin = rand(); cout << "new Person" << endl; } istream& operator>>( istream& _is, Person& _p) { _is >> _p.d_firstName >> _p.d_lastName >> _p.d_sin; // check for failure if ( !_is ) _p = Person(); return _is; } ostream& operator<<( ostream& _os, const Person& _p) { _os << _p.d_firstName << "\t" << _p.d_lastName << "\t"; _os << _p.d_sin; return _os; } int main() { fstream ioFile; Person personA, personB; // read personA from console cin >> personA; cout << "-------------------" << endl; // output personA to file ioFile.open( "people.txt", ios::out ); ioFile << personA; ioFile.close(); // read personB from file ioFile.open( "people.txt", ios::in ); ioFile >> personB; ioFile.close(); // output personB to console cout << "Person: " << personB << endl; return 0; }