0

I'm trying to write a function that will input information into a map from a text file. My main code goes as follows:

int main(){
    typedef map<int,student*> record;
    record allstudents;
    fileinput("inputtest.txt",allstudents);


    //rest of code....
}

where the function 'fileinput' is defined as:

void fileinput(string datafile, record map){ 
    fstream file1(datafile);
    if(!file1.good()){
    //error code
    }
    //Pulls information from file
    student* S1= new physics(name,ID); //creates a new pointer
    //(*S1).printinfo(); //Can print info if required for de-bug
    map[ID]=S1; //store to map
    entries++;  //counts entries read in            
    }
    cout<<"Import complete. "<<entries<<" new students entered."<<endl;
}

When I run this piece of code from a test file, it will read in the data and output it fine if I uncomment (*S1).printinfo(); and will correctly count the number of students that have been read in. However when I come back to my main function and output what is now stored in allstudents there appears to be nothing there?

Why is this occurring and does anybody know the way around this problem? I've cut a lot of code out to try and make it easier to read but if you need to see the rest I can always edit this.

Thanks.

QuantumO
  • 187
  • 2
  • 12

2 Answers2

2

This is because you are passing in map by value. Change the signature of the function to

void fileinput(string datafile, record &map)

Short explanation: when you pass by value, a copy of the argument (map) is made. Inside your function you perform modifications to that copy, but these modifications are lost when the function returns and the copy goes out of scope. They do not automatically propagate back to the "source" object.

For a detailed explanation, see Pass by Reference / Value in C++.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
2

You are passing the map by value, so the function makes it's own copy and your original remains unchanged. Try passing by reference:

void fileinput(string datafile, record& map) { ... }
                                      ^ reference! 
juanchopanza
  • 223,364
  • 34
  • 402
  • 480