jhrmdk
jhrmdk

Reputation: 642

C++ filling array of structure from file

Hi I need to read a file and get data from file to array of structure.

Structure

struct Activity {
    string ID;
    string Name;
    string quantity; };

I have this function for reading from file

int* fillStructure(ifstream &fileActivity){


    int i=0;
    int numberOfElements = numberOfLines(fileActivity);

    Activity* myActivity = new Activity[numberOfElements];

    while (i < numberOfElements)
    {
          getline(fileActivity, myAktivity[i].ID, ',');
          getline(fileActivity, myActivity[i].Name, ',');
          getline(fileActivity, myActivity[i].quantity, '\n');      
          i++;
    }

   fileActivity.close(); 
   return myActivity; }

And when i try in main function to print members of structures It doesnt work

int main(){



    if (!(fileActivity.is_open())){
        cout << "Error when reading file" << endl;
        return 0;
    }  

    fillStructure(fileActivity);

    cout << myActivity[1].ID << endl; return 0;  }

I am beginner, can you guys help me what I am doing wrong ?

Upvotes: 0

Views: 518

Answers (2)

bierschi
bierschi

Reputation: 322

You have to declare your return value in the main function.

struct Activity {
string ID;
string Name;
string quantitiy;
};

Activity* fillStructure(ifstream &fileActivity) {

int i = 0;
int numberOfElements = numberOfLines(fileActivity);
Activity* myActivity = new Activity[numberOfElements];

while (i < numberOfElements)
{
    getline(fileActivity, myActivity[i].ID, ',');
    getline(fileActivity, myActivity[i].Name, ',');
    getline(fileActivity, myActivity[i].quantitiy, '\n');
    i++;
}

fileActivity.close();

return myActivity;
}


int main(){

ifstream fileActivity ("test.txt", ifstream::in);
Activity* retFile;

retFile = fillStructure(fileActivity);

cout << retFile[1].ID << endl;

return 0;
}

Declare the return Type of the fillStructure function in the main function like this:

Activity* retFile;

This codesnippet works for me

Upvotes: 0

A.Andruhovski
A.Andruhovski

Reputation: 79

You declared myActivity in void fillStructure(ifstream &fileActivity), but trying to access from int main().

Upvotes: 3

Related Questions