在C++中读取动态数组的对象

问题描述 投票:0回答:1

我试图读取文件中的对象(在我的例子中是病人),并将它们制作成一个动态数组,我使用counter来计算文件中存储的对象,并根据计数器的大小创建一个数组。我的问题是,作为一个输出,我只得到最后一个项目,我存储在文件中多次(例如,如果我的计数器是6,输出是最后一个项目存储在文件中的6倍)。


  void patient::read_patient_DB()
    {   int counter = 0;
       fstream fp;
      patient p;
    cout << "\n\n\n\t\tDISPLAY ALL RECORD !!!\n\n";
    fp.open("patient.dat", ios:: in );
    while (fp.read((char *) & p, sizeof(patient)))
    {
        counter++;


    }
    cout<<"----The out patient group has ["<<counter<<"] data recorded----"<<endl;
    patient * pointer = new patient[counter];
    for(int i = 0;i <counter;i++)
    {
      pointer[i] = p;
     pointer[i].preview();

    }


    delete [] pointer;
    fp.close();

    }
c++ arrays dynamic-memory-allocation file-handling object-oriented-analysis
1个回答
0
投票

我的问题是,作为一个输出,我只得到最后一个项目,我存储在文件中多次

考虑到你从不修改 p 彼此 pointer[i] = p. 你需要做这样的事情。

while(read_from_file(p)) {
    pointer[i++] = p;
}
© www.soinside.com 2019 - 2024. All rights reserved.