1

我正在尝试将文本文件中的字符串值添加到向量中。在这样做的同时,我还在检查字符串中的字符数,然后当到达具有所需字符数的单词时,我将该字符串添加到向量中。

但是当我调试我的程序时,我一直看到越界异常,它打印出的字符串高于所需的字符数。

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);
    }
}
4

1 回答 1

2

长度为 2+ 或 7- 这听起来很奇怪。您的条件很可能应该是:

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

作为旁注,你最好阅读这样的词:

string word;
while(in >> word) {
  cout << word << endl;
  //push in selected words based on num of chars
  words.push_back(word);
}
于 2013-07-14T15:36:15.607 回答