2

I have followed instructions on the net and this code is suppose to add the inputs to the end of the file 'database'. But when i check, the data over rides the existing data. Please help, here is my code:

int main(){
    string name;
    string address;
    string handphone;
    cout << "Name: ";
    getline(cin, name);
    cout << "Address: ";
    getline(cin, address);
    cout << "Handphone Number: ";
    getline(cin, handphone);
    ofstream myfile("database", ios_base::ate);
    myfile.seekp( 0, ios_base::end );
    myfile << name<<endl;
    myfile << address<<endl;
    myfile << handphone<<endl;
    myfile.close();
}
Deckdyl
  • 103
  • 1
  • 2
  • 12
  • 1
    Try adding `out` to the _stream_ open mode... – K-ballo Dec 24 '12 at 06:16
  • 1
    As answered on [C++ Ofstream Overwriting][1], you need to use ios::app in ofstream flags. [1]: http://stackoverflow.com/questions/8220196/c-ofstream-overwriting – Ishan Arora Dec 24 '12 at 06:25

1 Answers1

3

Use:

ofstream myfile("database",  ios::out | ios::app);

ios::out: Open for output operations.

ios::app: All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.

Martin York
  • 257,169
  • 86
  • 333
  • 562
Alok Save
  • 202,538
  • 53
  • 430
  • 533