пытаюсь добавить слова из текстового файла в вектор, но получаю 'std :: out_of_range' - PullRequest
0 голосов
/ 15 ноября 2018

пытается добавить слова из этого текстового файла, но продолжает выдавать ошибку вне диапазона.Я думаю, что ошибка лежит где-то в циклах, но не удалось выяснить, почему она не работает.Помощь будет принята с благодарностью

#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 голосов
/ 15 ноября 2018

Ваш код сложный.Чтобы прочитать все слова (= разделенные пробелами) в 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';
}
...