2015-05-17 52 views
0

所以,這裏有一個奇怪的問題,我真的只是遇到了問題。我有一個字符串列表,我試圖看看它們中的兩個是否匹配。所以,我有一個遍歷並獲取每個字符串,另一個檢查它是否匹配。然而,它總是說這兩個都是真的 - 即使第一個在列表中沒有匹配。比較兩個字符串迭代器總是出現C++

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

對於爲什麼它總是正確的任何想法?

+4

'currentWord.compare(臨時)'等同於'currentWord = temp' - 你說的正好相反!你要。閱讀精美的手冊,描述'string :: compare'返回值的部分。 –

+0

修正了這個問題,'temp!=「」'==>'!temp.empty()',你可能想在你的兩部分佈爾表達式中使用* first *。 – WhozCraig

回答

3

您的問題與currentWord.compare(temp)string::compare()的返回類型爲int,如果它們相等(它的計算結果爲false),則返回類型爲0,如果它們不同(評估結果爲true),則返回正數或負數。

你想:

if((currentWord.compare(temp) == 0) && temp != "") { 
... 

你可以閱讀string::compare()這裏: http://www.cplusplus.com/reference/string/string/compare/