Results 1 to 2 of 2

Thread: Saving an object to a file

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Jan 2002
    Posts
    21

    Saving an object to a file

    What is wrong with this code? I keep getting errors saying

    error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class Account' (or there is no acceptable conversion)

    any help would be greatly appreciated.

    #include<iostream>
    #include<fstream>
    using namespace std ;

    class Account {
    protected:
    float Balance;
    char Accountno[5];
    public:
    Account(char id[5], float initialbal);
    ~Account();

    };
    Account::Account(char id[5], float initialbal)
    {
    strcpy(Accountno, id);
    Balance = initialbal;
    }

    Account::~Account(){}

    void main()
    {
    Account acc1("1234", 500);
    Account acc2("2345", 1000);

    fstream in_out ("acc.txt", ios::in|ios:ut);
    if (in_out.fail() )
    {
    cerr << "error opening acc.txt" <<endl;
    return ;
    }

    in_out << acc1 << acc2 ;

    in_out.seekg ( 0 );

    in_out >> acc1 >> acc2 ;
    cout << acc1 << acc2 ;
    }

  2. #2
    Zaei
    Guest
    Define an overloaded operator:
    Code:
    friend ostream& operator<<(ostream& os, Account& rhs)
    {
       os << rhs.<blah> << <etc>;
       return os;
    }
    Just os << each of the members that you want to write.

    Z.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width