比较两个字符串迭代器总是出现真正的C ++

时间:2015-05-17 02:11:05

标签: c++ string iterator

所以,这是一个奇怪的问题,我真的遇到了麻烦。我有一个字符串列表,我试图看看它们中的两个是否匹配。所以,我有一个迭代通过并获取每个字符串,另一个检查它是否匹配。但是,它总是说两者都是真的 - 即使第一个在列表中没有匹配。

for(iterator = tagList.begin(); iterator != tagList.end(); ++iterator)
{
  string theWord = *iterator;
  string currentWord = *iterator;
  if(currentWord[0] == '<' && currentWord[1] != '/')
  {
     bool matchFound = false;

     list<string>::const_iterator it2;
     for(it2 = (++iterator); it2 != tagList.end(); ++it2)
     {
        string temp = *it2;
        if(currentWord.compare(temp) && temp != "")
        {
           fixedString += theWord + ' ';
           matchFound = true;

           cout << "A match was found... Current string: " 
                << fixedString << endl;
           cout << "\tthe matched word was " << *it2 << endl;
           break;
        }
     }
     if(!matchFound)
     {
        currentWord = *iterator;
        currentWord = currentWord.substr(1, currentWord.size() - 2);
        fixedString += currentWord;
        cout << "No match was found... Current string: " << fixedString 
             << endl;
     }
  }
}

关于为何总是如此的任何想法?

1 个答案:

答案 0 :(得分:3)

您的问题出在currentWord.compare(temp)string::compare()的返回类型为int,如果它们相等(评估为false)将为0,如果它们不同(评估为{{,则为正或负数值) 1}})。

你想:

true

您可以在此处阅读if((currentWord.compare(temp) == 0) && temp != "") { ... http://www.cplusplus.com/reference/string/string/compare/