C++从文件中读取对象的数组属性

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

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

回答:

如果datafscanf模式固定,总是长度为4,你可以重复%ld(格式说明符long)的四倍。

fscanf(file, "%f%s%i%ld%ld%ld%ld", 

&PretUtilitati, &NumeUtilitati, &Numarachizitii,

&data[0], &data[1], &data[2], &data[3]);

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

以上是 C++从文件中读取对象的数组属性 的全部内容, 来源链接: utcz.com/qa/264774.html

回到顶部