Mega Code Archive

 
Categories / C++ / File
 

Save and read class back and forth to a file

#include <iostream> #include <fstream> #include <cstring> using namespace std; class Person {   char name[80];   char areaCode[4];   char prefix[4];   char num[5]; public:   Person() { };   Person(char *n, char *a, char *p, char *nm)   {     strcpy(name, n);     strcpy(areaCode, a);     strcpy(prefix, p);     strcpy(num, nm);   }   friend ostream &operator<<(ostream &stream, Person o);   friend istream &operator>>(istream &stream, Person &o); }; ostream &operator<<(ostream &stream, Person o) {   stream << o.name << " ";   stream << "(" << o.areaCode << ") ";   stream << o.prefix << "-";   stream << o.num << endl;   return stream; // must return stream } istream &operator>>(istream &stream, Person &o) {   cout << "Enter name: ";   stream >> o.name;   cout << "Enter area code: ";   stream >> o.areaCode;   cout << "Enter prefix: ";   stream >> o.prefix;   cout << "Enter number: ";   stream >> o.num;   cout << endl;   return stream; } int main() {   Person personObject;   char c;   fstream pb("phone", ios::in | ios::out | ios::app);   if(!pb) {     cout << "Cannot open phone book file.\n";     return 1;   }   for(;;) {     do {       cout << "1. Enter numbers\n";       cout << "2. Display numbers\n";       cout << "3. Quit\n";       cout << "\nEnter a choice: ";       cin >> c;     } while(c < '1' || c > '3');     switch(c) {       case '1':         cin >> personObject;         cout << "Entry is: ";         cout << personObject;                                pb << personObject;                                  break;       case '2':         char ch;         pb.seekg(0, ios::beg);         while(!pb.eof()) {           pb.get(ch);           if(!pb.eof())               cout << ch;         }         pb.clear();                               cout << endl;         break;       case '3':         pb.close();         return 0;     }   } }