Bon Kurie
Bon Kurie

Reputation: 35

Reading from a text file properly

I am reading string from a line in a text file and for some reason the the code will not read the whole text file. It reads to some random point and then stops and leaves out several words from a line or a few lines. Here is my code.

string total;
 while(file >> word){
    if(total.size() <= 40){
        total +=  ' ' + word;
    }
    else{
        my_vector.push_back(total);
        total.clear();
    }

Here is an example of a file

The programme certifies that all nutritional supplements and/or ingredients that bear the Informed-Sport logo have been tested for banned substances by the world class sports anti-doping lab, LGC. Athletes choosing to use supplements can use the search function above to find products that have been through this rigorous certification process.

It reads until "through" and leaves out the last four words.

I expected the output to be the whole file. not just part of it. This is how I printed the vector.

for(int x = 0; x< my_vector.size(); ++x){
    cout << my_vector[x];
    }

Upvotes: 0

Views: 102

Answers (3)

Abdullah
Abdullah

Reputation: 2111

You missed two things here:

First: in case when total.size() is not <= 40 i.e >40 it moves to else part where you just update your my_vector but ignore the current data in word which you read from the file. You actually need to to update the total after total.clear().

Second: when your loop is terminated you ignore the data in word as well. you need to consider that and push_back()in vector (if req, depends on your program logic).

So overall you code is gonna look like this.

string total;
while(file >> word)
{
    if(total.size() <= 40)
    {
        total +=  ' ' + word;
    }
    else
    {
        my_vector.push_back(total);
        total.clear();
        total +=  ' ' + word;
    }
}
my_vector.push_back(total);//this step depends on your logic 
                           //that what u actually want to do

Upvotes: 3

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153792

There are two problems:

  1. When 40 < total.size() only total is pushed to my_vector but the current word is not. You should probably unconditionally append the word to total and then my_vector.push_back(total) if 40 < total.size().
  2. When the loop terminated you still need to push_back() the content of total as it may not have reached a size of more than 40. That is, if total is no-empty after the loop terminated, you still need to append it to my_vector.

Upvotes: 0

The Dark
The Dark

Reputation: 8514

Your loop finishes when the end of file is read. However at this point you still have data in total. Add something like this after the loop:

if(!total.empty()) {
    my_vector.push_back(total);
}

to add the last bit to the vector.

Upvotes: 0

Related Questions