When you do fileStream>>help
, that's not changing the value of the pointer, it is overwriting the contents of the string that the pointer is pointing at. So you are pushing the same pointer into the vector over and over again. So all of the pointers in the vector point to the same string. And since the last thing written into that string was the word "day", that is what you get when you print out each element of your vector.
Use a vector of std::string
instead:
string help;
vector<string> MyVector;
If, as you say, you must stick with vector<char*>
, then you will have to dynamically allocate a new string for each element. You cannot safely use a char*
with operator>>
, because there is no way to tell it how much space you actually have in your string, so I will use std::string
for at least the input.
std::string help;
vector<char*> MyVector;
while (fileStream>>help) {
char * p = new char[help.size() + 1];
strcpy(p, help.c_str());
MyVector.push_back(p);
}
Of course, when you are done with the vector, you can't just let it go out of scope. You need to delete every element manually in a loop. However, this is still not completely safe, because your memory allocation could throw an exception, causing whatever strings you have already allocated and put in the vector to leak. So you should really wrap this all up in a try block and be ready to catch std::bad_alloc
.
This is all a lot of hassle. If you could explain why you think you need to use vector<char*>
, I bet someone could show you why you don't.