I am stuck on a homework assignment. I have to read text from a file, allocate each word to memory, then user a pointer to send it to a vector<string*>. My program keeps overwriting the vector with the new word from the file instead of just adding it. I can’t figure out why this is happening.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
void WordFunctions(string *pstr, vector<string*> &words)
{
words.push_back(pstr);
}
int main(){
ifstream file;
vector<string*> a;
string word;
int w =0;
file.open("word.txt");
while (!file.eof())
{
w++;
file >> word;
WordFunctions(&word, a);
}
file.close();
for (int i=0;i<10;i++){
cout<<(*a[i])<<" ";
delete a[i];
}
system ("pause");
}
Either use a
vector<string>or allocate the new string on the heap: