试图将文本文件中的单词添加到向量中,但不断抛出“ std :: out_of_range”

时间:2018-11-14 21:19:20

标签: c++ vector fstream

试图从该文本文件中添加单词,但不断抛出超出范围的错误。我认为该错误位于循环中,但是还无法弄清为什么它不起作用。帮助将不胜感激

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

struct WordCount{
    string word;
    int count;
};

int main () {
    vector<WordCount> eggsHam;

    ifstream readFile ("NewTextDocument.txt");
    int counter = 0;
    int holder;
    string lineRead;
    WordCount word;

    if(readFile.is_open()){
        //add all the words into a vector
        while (getline(readFile, lineRead)){
            holder = counter;
            for(int i = 0; i < lineRead.length(); ++i) {
                if (lineRead.at(i) != ' ') {
                    ++counter;
                }
                if (lineRead.at(i) != ' ') {
                    for (int k = 0; k < (counter - holder); ++k) {
                        word.word.at(k) = lineRead.at(holder + k);
                    }
                    eggsHam.push_back(word);
                    ++counter;
                }
            }
        }

        readFile.close();
    }
    else cout << "Unable to open file";

    return 0;
}

1 个答案:

答案 0 :(得分:0)

您的代码很复杂。要将所有单词(=空格分隔的事物)读入std::vector<std::string>,只需执行以下操作:

#include <cstdlib>
#include <vector>
#include <string>
#include <iterator>
#include <fstream>
#include <iostream>

int main()
{
    char const *filename = "test.txt";
    std::ifstream is{ filename };

    if (!is.is_open()) {
        std::cerr << "Couldn't open \"" << filename << "\" for reading :(\n\n";
        return EXIT_FAILURE;
    }

    std::vector<std::string> words{ std::istream_iterator<std::string>{ is },
                                    std::istream_iterator<std::string>{} };

    for (auto const &w : words)
        std::cout << w << '\n';
}