1

I'm trying to add string values from a text file to a vector. While doing that, I'm also checking the strings for the number of characters then when reach the word with the desired number of characters, I then add that string into the vector.

But when I'm debugging my program, I keep seeing out of bounds exception and it prints out strings higher than the desired number of characters.

vector<string> words;
vector<string> chosenWords;
ifstream in("WordDatabase.txt");

while(in) {
  string word;
  in >> word;
  cout << word << endl;
  //push in selected words based on num of chars
  words.push_back(word);
}

for(vector<string>::iterator itr=words.begin(); itr!=words.end();++itr)
{
    if((*itr).length() >= 2 || (*itr).length() <= 7)
    {
        cout << (*itr) << endl;
        chosenWords.push_back(*itr);
    }
}
Ryan Haining
  • 30,835
  • 10
  • 95
  • 145
Joel Seah
  • 624
  • 3
  • 12
  • 33

1 Answers1

2

Lengths that are 2+ or 7- that sounds like a weird condition. Most likely your conditional should be:

if((*itr).length() >= 2 && (*itr).length() <= 7)

As a side note, you're better off reading words like this:

string word;
while(in >> word) {
  cout << word << endl;
  //push in selected words based on num of chars
  words.push_back(word);
}
Borgleader
  • 15,349
  • 5
  • 42
  • 59
  • What's the difference? Sorry if i sound noobish coz i only started c++ 2-3 weeks ago. – Joel Seah Jul 14 '13 at 15:37
  • I believe that this version covers edge cases that your version doesn't. I'd have to dig to find the specific answer to this but if you roam SO enough you'll find that this is the canonical way of doing things. – Borgleader Jul 14 '13 at 15:40
  • @JoelSeah: Your `while (in)` loop is wrong for the same reason `while (!in.eof())` is wrong. See: [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/q/5605125/445976) – Blastfurnace Jul 14 '13 at 16:08