繁体   English   中英

如何保存文件中的所有数据? C++

[英]How to save all data in the file? C++

我遇到了问题,我想将所有 ID 号保存在文本文件中,但它只保存用户输入的最后一个 ID 号。

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{

    string line;
    int idnum;
    ofstream IdData ("data.txt");

    cout<<" Enter your ID number: "<<endl;
    cin>>idnum;

    if(IdData.is_open())
    {
        IdData<< "ID number of voter is: ";
        IdData << idnum << endl;
        IdData.close();
    }
    else 
        cout<<" Unable to open file";


    ifstream Data ("data.txt");

    if(Data.is_open())
    {
        while (getline (Data, line))
        {
            cout<< line << endl;
        }

        Data.close();
    }
    else
        cout<<" Unable to open file";
}

您只要求用户提供 1 个 ID,然后用包含该 1 个 ID 的新文件覆盖现有文件。

std::ofstream会破坏现有文件的内容,除非您明确要求它不要这样做。 因此,对于您正在尝试做的事情, append在现有文件末尾添加一个新 ID,您需要在打开std::ofstream时包含appate标志(请参阅C++ Filehandling: Difference between Z9E304D:9918DF18424CFA和 ios::ate? ),例如:

ofstream IdData ("data.txt", ios::app);

或者:

ofstream IdData ("data.txt", ios::ate);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM