从文本文件中添加单词到 C++ 向量

4

我正在尝试将文件中的每个单词添加到向量中,但如果我将向量的大小设置为500,而文件中只有20个单词,则向量的大小仍被视为500。如何解决这个问题?

我这样做是否有问题?能否简化此过程?

void loadFile(string fileName)
{
    vector<string> fileContents(500);
    int p = 0;
    ifstream file;
    file.open(fileName);
    if (!file.is_open()) return;

    string word;
    while (file >> word)
    {
        fileContents[p] = word;
        p++;
    }

    for (int i = 0; i < fileContents.size(); i++)
    {
        cout << fileContents[i] << endl;
    }  
}

2
你应该使用 fileContents.push_back(word); 而不是 fileContents[p] = word;,同时将 vector<string> fileContents(500); 改为 vector<string> fileContents; 并且去掉 p - drescherjm
1
@drescherjm 我试过了,但是当它要打印文件内容时,什么都没有打印出来。编辑:算了,我把命令输错了..那个方法有效..我以为我之前试过了,但是我想我一开始就输错了 - jake
2
@jake 你把(500)去掉了吗? - David G
1
现在它可以工作了。我想上次尝试时可能忘记了那个,也许这就是为什么它没有工作的原因。@0x499602D2 - jake
2个回答

4
您也可以采用更直接的方法,立即从输入流中复制。
std::vector<std::string> loadFile(std::string fileName) {
    std::ifstream file(fileName);
    assert(file);

    std::vector<std::string> fileContents;
    std::copy(std::istream_iterator<std::string>(file), 
              std::istream_iterator<std::string>(), 
              std::back_inserter(fileContents));

    return fileContents;
}

3

@drescherjm在评论中给出了正确答案。

void loadFile(string fileName)
{
    vector<string> fileContents;
    ifstream file;
    file.open(fileName);
    if (!file.is_open()) return;

    string word;
    while (file >> word)
    {
        fileContents.push_back(word);
    }

    for (int i = 0; i < fileContents.size(); i++)
    {
        cout << fileContents[i] << endl;
    }  
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接