I am making a game where the user is allowed to choose a Player
object from a vector of Player
objects read in from a text file.
I ask the user to enter a name in order to choose a player from the vector and I iterate through the vector to look for a matching name (assume each player has a different name).
Once they match, I want to point my Player
player1
pointer to that object in the player vector.
However, the player1
pointer is not printing the correct name outside of the for loop after it has found a match. The pointer instead defaults to printing the name of the last player in the text file every time rather than the name of the player that matches the input of the user.
What could I do to fix this issue ?
vector<Player> playerVectorReadIn;
Player *player1; string name="";
//reading in the data
ifstream inFile;
inFile.open("playerData.txt");
if(!inFile){
cout<<"Error! Unable to open file";
exit(1);
}
while(inFile>>name){
Player playerObject(name);
playerVectorReadIn.push_back(playerObject);
}
inFile.close();
//finding matching data in vector
cout<<"\n\tEnter the name of the player from the list you choose: ";
getline(cin,name);
for(Player p:playerVectorReadIn){
if(p.getName()==name){
flag=true;
player1=&p; //setting pointer to player - https://stackoverflow.com/questions/2988273/c-pointer-to-objects
cout<<name; //the user entered name (example Bob)
cout<<p.getName(); //the matching name in the vector (Bob)
//both print the same name here so it works
}
}
if(flag==true){
cout<<"\nYou will be playing as: "<<player1->getName();
//prints as the name of the last object in the text file (example Ryan)
//not the matching name as above - why?
}else{
cout<<"\nPlayer not found.";
}
flag=false; name="";
Text file contents example :
Dave
Jill
Bob
Mary
Donna
Ryan