加载对象数组时C ++程序崩溃了

时间:2013-12-23 21:04:37

标签: file io

您好我正在尝试用c ++中的文本文件填充对象数组,但每次运行程序时都会崩溃。我是在正确的方向吗?有没有更有效的方法呢?

的main.cpp

#include <iostream>
#include <string>
#include <stdio.h>
#include <fstream>
#include "Item.h"

using namespace std;

void readItems(FILE *products, Item pList[]);

FILE *products;
int main()
{

    Item pList[5];

    readItems(products,pList);
    return 0;
}

void readItems(FILE *products, Item pList[]){

products = fopen("data.txt", "r");

int i = 0;
fread(&pList[i], sizeof(pList), 1, products);
while (!feof(products))
{
    i++;
fread (&pList[i], sizeof(pList), 1, products);

}

fclose(products);
}

Item.cpp

#include "Item.h"
#include <stdio.h>
#include <string>
#include <conio.h>
#include <iostream>

using namespace std;

Item::Item()
{
    code = 0;
    description = "";
    price = 0;
}

Item::Item(int code1,string description1,float price1)
{
    code = code1;
    description = description1;
    price = price1;
}

void Item::printData(){
    cout<<endl<<"Code:"<<code<<"\tName:"<<description<<"\tPrice:"<<price;
}

void Item::setData(int code1,string description1,float price1){
    code = code1;
    description = description1;
    price = price1;
}

int Item::getCode(){
    return code;
}

float Item::getPrice(){
    return price;
}

Item::~Item()
{
    //dtor
}

新代码就是这样,但是它打印了一些txt文件的一些字符和一些奇怪的符号。

void readItems(FILE *fin, Item list[]){
    int i=0;

    products = fopen("items.txt","r");
    fread(&list[i],sizeof(list[i]),1,products);
    list[i].printData();
    while(!feof(products) && i<5){
            fread(&list[i],sizeof(list[i]),1,products);
            list[i].printData();
            i++;
}

    fclose(products);
}

2 个答案:

答案 0 :(得分:0)

尝试替换

while (!feof(products))
{
    i++;
fread (&pList[i], sizeof(pList), 1, products);

}

while (!feof(products) && (i < 5))
{
    i++;
fread (&pList[i], sizeof(pList), 1, products);

}

答案 1 :(得分:0)

这是我填充数组的方式。我认为你得到那些奇怪的符号,因为 fread(&amp; list [i],sizeof(list [i]),1,products); 从文件中读取 sizeof的一个元素( list [i]) bytes,所以你在数组中得到一个元素,其他任何东西都是垃圾。解决方案是在三个元素中设置不同的大小(字节)。所以尝试 fread(&amp; list [i],5,3,fin)。我不确定,我在我的代码中使用fscanf并且像魅力一样工作!

void readItems(FILE *fin,Item list[])
{
    int i=0;
    int code;
    char description[15];
    float price;

    fin=fopen("items.txt", "r");

    fscanf (fin,"%i %15[a-zA-Z ]s",&code,description);
    fscanf (fin,"%f",&price);
    list[i].setData(code,description,price);

    while (!feof(fin)&&i<5)
    {
       i++;
       fscanf (fin,"%i %15[a-zA-Z ]s",&code,description);
       fscanf (fin,"%f",&price);
       list[i].setData(code,description,price);
    }
    fclose(fin);
}