tags:

views:

124

answers:

2

Hi,

Beginner question here:

im reading a file, storing the feilds into struct members, then storing the name of the struct into a vector.

I output the size of my vector and debug it to see if it worked and i have the feilds from the file isolated.

im doing this in a vector *ptrFunc() function.

and i return the &vectorObject so i dont need to use a vector type ptr obj declaration.

Moving from one function to the other, even with my return type, do i need to parse the file all over again?

Heres some code, im dont think im being very clear:

  //Varaible Declartions/Intializations
  //Open File

   vector<myStruct> *firstFunc()
   {

    while ( !inFile->eof() )
    {
 // Isolating each feild delimited by commas
 getline( *inFile, str1, ',' );
 myStruct.f1 = str1;

 getline( *inFile, str2, ',' );
 myStruct.f2 = str2;

 getline( *inFile, str3, ',' );
 myStruct.f3 =  atof( str3.c_str()  );

 getline( *inFile, str4 );
 myStruct.f4 = atof( str4.c_str() );

 v.push_back( myStruct );
       // We have the isolated feilds in the vector...
       // so we dance
        }
     return &v;
      }
   // Now do i still have to do the getlines and push_back with the vector again in  another function?

   vector<myStruct> *otherFunc()
   {
      sStruct myStruct;
      vector<myStruct> *v = firstFunc(),
      vInit;
      v = &vInit
      vInit.push_back( myStruct );
      ...

so thats where i debug it and my Structure Members have lost all data!

What should i prolly do in the first function so that my struct members do not lose their data?

My guess is to just create a void function or something. But then storing that into a vector would then be the problem.

Im just have scoping issues. :p

+1  A: 

Is it perhaps so that the vector 'v' you return from firstFunc() is allocated on the stack? If so, then that's probably your problem, since you're returning the address of an object that is going out of scope as the function exits.

So fix that, return the vector by value, or create it on the heap using new.

unwind
+2  A: 

Declare your functions this way:

void firstFunc(vector<myStruct> &v) 
{
...
}

void otherFunc(vector<myStruct> &v) 
{
...
}

and use them this way

void foo()
{
vector<myStruct> v;
firstFunc(v);
otherFunc(v);
}
Wacek