从文本文件中读取的对象数组中最后丢失的数据

Last data missing in an object array read from text file

本文关键字:最后 数据 数组 对象 文本 读取 文件      更新时间:2023-10-16

这是一个家庭作业项目,用户与数据库交互,数据库中有数据,如号码,街道名称等,这些数据驻留在文本文件中。

一些菜单选项要求程序读取或操作该数据,例如显示选项。我通过打开fstream并将数据放入数据类型为预先声明的结构体resident的临时数组来实现这一点。

//reopen file
fstream listeResidents1;
listeResidents1.open("listeResidents.dat",ios::out|ios::in|ios::binary);
//Create a temporary array of objects resident for manipulation
resident tabRes1[nombreResid-1];
//Insertion des objets resident du registre dans le tableau temporaire
for (int h = 0;h < nombreResid;h++)
{
    listeResidents1.seekg((h)*sizeof(resident));
    listeResidents1.read(reinterpret_cast<char*>(&tabRes1[h]),sizeof(resident));
}
listeResidents1.close();

My Display()函数做这个^^^,然后使用for循环遍历数组中的每个对象并显示它们的所有属性。然而,最后一个条目有倒数第二个字符串缺少一些字符和最后一个变量,一个浮点数,设置为0(这意味着它也被截断),我不知道为什么。有人知道为什么会这样吗?

作为一个可视化的例子,最后一个条目被成功写入文件,具有以下属性:

int numero: 4
[the other,correctly displayed attributes here]
char rue[30]: queen
float superf: 80

显示时,最后一项将显示

numero: 4
[the other,correctly displayed attributes here]
rue: que
superf: 0

如果我添加另一个条目,它是截断的,而4现在正确显示…

编辑:这是结构体。

struct resident
    {
        int numero;
        char nom[30];
        char prenom[30];
        int numciv;
        char rue[30];
        float superf;
    };

您正在读取nombreResid项到内存中,但您的缓冲区resident tabRes1[nombreResid-1]只有nombreResid-1项的空间。