【问题标题】:reading an object with dynamic array in c++在 C++ 中读取具有动态数组的对象
【发布时间】:2020-05-09 22:33:49
【问题描述】:

我正在尝试读取对象文件(在我的情况下为患者)并制作它们的动态数组。 我使用计数器来计算存储在文件中的对象,并根据该计数器大小创建一个数组。 我的问题是作为一个输出,我只得到了我多次存储在文件中的最后一个项目(例如,如果我的计数器是 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++ 中,“动态数组”拼写为 std::vector。有了它,您将无需事先计算记录。
  • pointer[i] = p; -- 所以你将数组中的每个值都设置为相同的p,你想知道为什么数组中的每个值都相同?你问的是这个吗?

标签: c++ arrays dynamic-memory-allocation file-handling object-oriented-analysis


【解决方案1】:

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

考虑到您永远不会在每个 pointer[i] = p 之间修改 p,这是有道理的。你需要做这样的事情:

while(read_from_file(p)) {
    pointer[i++] = p;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 2017-02-07
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多