c ++从具有数组属性

时间:2017-12-27 11:44:50

标签: c++ oop

我有一个类,我想将对象读入一个对象数组,但我的类属性有问题(长数据[4];)。我不知道怎么读它。在Read方法中,我想从文件中读取所有属性,并创建数据元素的向量,并在构造函数中附加从文件中读取的向量。

//Class:
class Utilitati{
    const int id;
    float PretUtilitati;
    char * NumeUtilitati;
    int Numarachizitii;
    long data[4];  --This is the problem( I dont know how can i read it )


//Constructor:
    Utilitati(float PretUtilitati, char * NumeUtilitati, int Numarachizitii, long data[]) :id(3){
        this->PretUtilitati = PretUtilitati;
        this->NumeUtilitati = new char[strlen(NumeUtilitati) + 1];
        strcpy(this->NumeUtilitati, NumeUtilitati);
        this->Numarachizitii = Numarachizitii;
        for (int i = 0; i < Numarachizitii; i++)
            this->data[i] = data[i];
    }

Data must be a vector from file.
//Read Method:
void citireFisier(char *numeFisier, Utilitati ** vectUtilitati)
{
    FILE* file = fopen(numeFisier, "r+");
    if (!file)
        cout << "\nEroare citire!" << endl;
    else
    {
        int contor = 0;
        float PretUtilitati;
        char NumeUtilitati[20];
        int Numarachizitii;
        long data[4];

        while (!feof(file))
        {
            fscanf(file, "%f%s%i%l", &PretUtilitati, &NumeUtilitati, &Numarachizitii, &data);
            Utilitati* NewUtilitati = new Utilitati(PretUtilitati, NumeUtilitati, Numarachizitii,data);
            vectUtilitati[contor++] = NewUtilitati;
        }
    }
}
   The file has the next format: 
    100   //float PretUtilitati
    Gaze   //char * NumeUtilitati;
    3      // int Numarachizitii;
    20171012  //long data[0];
    20151012   ////long data[2];
    20011023   ///long data[Numarachizitii];

1 个答案:

答案 0 :(得分:0)

如果您的data已修复且长度始终为4,则可以%ld模式重复longfscanf的格式说明符)四次。

fscanf(file, "%f%s%i%ld%ld%ld%ld",
    &PretUtilitati, &NumeUtilitati, &Numarachizitii,
    &data[0], &data[1], &data[2], &data[3]);

如果它不是固定长度,你应该先读取它的长度,然后使用循环fscanf条目。