user3239138
user3239138

Reputation: 143

creating vectors for individually parsed sentences c++

class Read
{
public:
    Read(const char* filename)
    :mFile(filename)
    {

    }
    void setString()
    {
        while(getline(mFile, str, '.'))
        {
            getline(mFile, str, '.');
            str.erase(std::remove(str.begin(), str.end(), '\n'), str.end());
        }

    }
private:
    ifstream mFile;
    string str;
};


int main()
{
    Read r("sample.txt");
    return 0;
}

My ultimate goal is to parse through each sentence in the file so I used getline setting the delimiter to '.' to get each individual sentence. I want to create a sentence vector but am not really sure how to do so.

The file is pretty big so it will have a lot of sentences. How do I create a vector for each sentence?

Will it simply be vector < string > str? How will it know the size?

EDIT: I added a line of code to remove the '\n' EDIT: Got rid of !eof

Upvotes: 0

Views: 89

Answers (3)

HadeS
HadeS

Reputation: 2038

Vectors are dynamica arrays. You need not to worry about the size of the vector. You can use push_back() function to add element in the vector. I have made some changes in your code. Please check if this work for you..

#include<vector>
using namespace std;
class Read
{
public:
    Read(const char* filename)
    :mFile(filename)
    {

    }
    void setString()
    {
        while(getline(mFile, str, '.'))
        {
            vec.push_back(str);
        }
    }
private:
    ifstream mFile;
    string str;
    vector<string> vec;
};
int main()
{
    Read r("sample.txt");
    return 0;
}

Upvotes: 2

Tony Delroy
Tony Delroy

Reputation: 106096

while(!myFile.eof())
        getline(mFile, str, '.');

Where did you find that? Please put it back. Try:

std::vector<std::string> sentences;

while(std::getline(mFile, str, '.'))
    sentences.push_back(str);

The vector container has a .size() function to return the number of populated elements. You should google "std::vector" and read through the functions in the API.

Upvotes: 2

Evgeny Sobolev
Evgeny Sobolev

Reputation: 543

#include <vector>
using namespace std;

...

vector<string> sentences;
sentences.push_back(line);

The vector is a dynamic array and it will resize itself as you keep adding sentences. If you know the number of sentences, you can increase the performance by calling:

sentences.resize(number of sentences here)

Upvotes: 1

Related Questions