user1069738
user1069738

Reputation: 33

Vector values assign

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.

Upvotes: 0

Views: 506

Answers (2)

Benjamin Lindley
Benjamin Lindley

Reputation: 103733

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.

Upvotes: 6

Jesse Good
Jesse Good

Reputation: 52365

Thats because your char * are all pointing at the same object. The help pointer and the pointers stored in the vector all point to the same object. Everytime you read from the stream it modifies what all the pointers are pointing at. Change char* to an std::string.

Upvotes: 3

Related Questions