C++ 将文本文件中的单词添加到向量c++;

C++ 将文本文件中的单词添加到向量c++;,c++,list,c++11,vector,C++,List,C++11,Vector,我试图将文件中的每个单词添加到一个向量中,但是如果我将向量的大小设置为(500),那么文件中只有20个单词。向量的大小仍然被认为是500。我该如何解决这个问题 我这样做是不是很糟糕?这能简化吗 void loadFile(string fileName) { vector<string> fileContents(500); int p = 0; ifstream file; file.open(fileName); if (!file.is_

我试图将文件中的每个单词添加到一个向量中,但是如果我将向量的大小设置为(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;
    }  
}
void加载文件(字符串文件名)
{
矢量文件内容(500);
int p=0;
ifstream文件;
打开(文件名);
如果(!file.is_open())返回;
字符串字;
while(文件>>word)
{
fileContents[p]=word;
p++;
}
对于(int i=0;icout@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;
    }  
}
void加载文件(字符串文件名)
{
矢量文件内容;
ifstream文件;
打开(文件名);
如果(!file.is_open())返回;
字符串字;
while(文件>>word)
{
文件内容。推回(word);
}
对于(int i=0;icout您还可以使用更直接的方法,即立即从输入流复制

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;
}
std::vector加载文件(std::string文件名){
std::ifstream文件(文件名);
断言(文件);
向量文件内容;
std::copy(std::istream_迭代器(文件),
std::istream_迭代器(),
std::back_插入器(fileContents));
返回文件内容;
}

你应该使用
文件内容。向后推(word);
而不是
文件内容[p]=word;
也可以更改
矢量文件内容(500);
向量文件内容;
并摆脱
p
@drescherjm我试过了,但当它打印文件内容时,它什么也不打印?编辑:NVM。我键入的命令错误..这很有效..我想我试过了,但我想我第一次键入的是错误的place@jake你把
(500)去掉了吗
?它现在可以工作了。我想我上次尝试时可能忘了它,也许这就是它不能工作的原因。@0x499602D2