0

我有这段代码:

    while(fileStream>>help)
    {
        MyVector.push_back(help);
    }

...并且可以说在文件“fileStream”中是 1 句话:今天是晴天。现在当我这样做时:

    for(int i=0;i<MyVector.size();i++)
    {
         printf("%s\n", MyVector[i]);
    }

,结果是“一天一天一天一天”。当然,它不应该是这样的。变量声明如下:

    char *help;
    vector<char*> MyVector;

编辑:我明白答案,谢谢...但是有什么方法可以将文件中的单词存储在vector<char*> MyVector其中(就像我首先想要的那样)。这对我的程序的其余部分来说会很棒。

4

2 回答 2

6

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.

于 2012-05-08T23:58:51.320 回答
3

那是因为你char *都指向同一个对象。指针和存储在向量中的help指针都指向同一个对象。每次您从流中读取时,它都会修改所有指针指向的内容。更改char*std::string.

于 2012-05-08T23:59:15.413 回答