5

我被困在家庭作业上。我必须从文件中读取文本,将每个单词分配到内存,然后使用指针将其发送到vector<string*>. 我的程序不断用文件中的新词覆盖向量,而不是仅仅添加它。我无法弄清楚为什么会这样。

#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");
}
4

3 回答 3

3

在堆上使用vector<string>或分配新字符串:

void WordFunctions(string *pstr, vector<string*> &words)
{
    words.push_back(new string(*pstr));
}
于 2012-11-01T23:39:34.450 回答
1

You are pushing the same element into vector which is the address of word. I massage a bit on your code

// pass reference to eliminate copy
void WordFunctions(string &str, vector<string> &words)
{
    words.push_back(str);
}
int main(){
    ifstream file;
    vector<string> a;  // you want to store string not the address of the string
    string word;
    int w =0;
    file.open("words.txt");
    while (!file.eof())
    {
        w++;
        word.clear();   // clear the content before store something into it
        file >> word;
        WordFunctions(word, a);
    }
    file.close();

     for (size_t i=0;i<a.size();i++){  // use size instead of hard code magic number
        cout<<(a.at(i))<<" ";  // use at function instead of []
    }

     system ("pause");
}
于 2012-11-01T23:52:10.183 回答
-1

您的word字符串在内存中始终具有相同的地址,因此在循环中您正在更改字符串的值,但随后您调用WordFunctions始终将相同的地址传递给他。

如果它是使用vector<string*>而不是的约束vector<string>,您可能需要为循环中的新字符串分配内存,将您的单词复制到那里,然后将新引用传递给WordFunctions

char *wordPtr

while (!file.eof())
{
    w++;
    file >> word;

    wordPtr = (char *)malloc((strlen(word)+1)*sizeof(char));
    strcpy(wordPtr, *word);

    WordFunctions(wordPtr, a);
}
于 2012-11-01T23:54:26.487 回答