从文本文件中读取的对象数组中缺少最后一个数据

时间:2014-08-10 05:09:20

标签: c++ arrays struct text-files truncated

这是一个家庭作业项目,用户可以与拥有数据,街道名称等数据的人员数据库进行交互。这些数据位于文本文件中。

某些菜单选项要求程序读取或操作该数据,例如“显示”选项。我通过打开一个fstream并将数据放入一个临时数组来完成此操作,该数组类型包含预先声明的struct驻留数据。

//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;
    };

1 个答案:

答案 0 :(得分:0)

您正在将nombreResid项目读入内存,但您的缓冲区resident tabRes1[nombreResid-1]只能容纳nombreResid-1个项目。