问题
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();
}
回答1:
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.
来源:https://stackoverflow.com/questions/14017724/how-do-i-add-data-at-the-end-of-a-file-in-c