【发布时间】: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