I have this piece of code:
while(fileStream>>help)
{
MyVector.push_back(help);
}
…and lets say that in file “fileStream” is 1 sentence: Today is a sunny day. Now when i do this:
for(int i=0;i<MyVector.size();i++)
{
printf("%s\n", MyVector[i]);
}
, the resoult is “day day day day day”. And, of course, it shouldnt be like that. Variables are declared like this:
char *help;
vector<char*> MyVector;
EDIT:i understand the answers, thank you…but is there any way to store words from file in vector<char*> MyVector(like i wanted in the first place). it would be great for the rest of my program.
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::stringinstead: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 achar*withoperator>>, because there is no way to tell it how much space you actually have in your string, so I will usestd::stringfor at least the input.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.