How do I add data at the end of a file in C++?

巧了我就是萌 提交于 2019-12-11 03:34:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!