2014-02-26 35 views
0

我是一位C#程序員,最近想研究更低層次的東西,所以上週開始學習C++,但偶然發現了一些我認爲很簡單的東西....我意識到我的代碼可能是醜陋如此裸露在我身邊!初學C++ - 字符串比較

我輸入以下字符串到我的程序:

「這是一個測試這個測試」,並期望在wordStructList包含4個單詞的列表,以「測試」和出現「本」設置爲2.當調試但是,字符串比較(我試過.compare和==)總是似乎增加發生的值,無論比較是否爲真。

例如currentName =「is」 word =「this」

但發生的事件仍然增加。

#include "stdafx.h" 

using std::string; 
using std::vector; 
using std::find; 
using std::distance; 

struct Word 
{ 
    string name; 
    int occurrences; 
}; 

struct find_word : std::unary_function<Word, bool> 
{ 
    string name; 
    find_word(string name):name(name) { } 
    bool operator()(Word const& w) const 
    { 
     return w.name == name; 
    } 
}; 

Word GetWordStruct(string name) 
{ 
    Word word; 

    word.name = name; 
    word.occurrences = 1; 

    return word; 
} 

int main(int argc, char argv[]) 
{ 
string s; 
string delimiter = " "; 
vector<string> wordStringList; 

getline(std::cin, s); 

do 
{ 
    wordStringList.push_back(s.substr(0, s.find(delimiter))); 
    s.erase(0, s.find(delimiter) + delimiter.length()); 

    if (s.find(delimiter) == -1) 
    { 
     wordStringList.push_back(s); 
     s = ""; 
    } 

} while (s != ""); 

vector<Word> wordStructList; 

for (int i = 0; i < wordStringList.size(); i++) 
{ 
    Word newWord; 

    vector<Word>::iterator it = find_if(wordStructList.begin(), wordStructList.end(), find_word(wordStringList[i])); 

    if (it == wordStructList.end()) 
     wordStructList.push_back(GetWordStruct(wordStringList[i])); 
    else 
    { 
     string word(wordStringList[i]); 

     for (vector<Word>::size_type j = 0; j != wordStructList.size(); ++j) 
     { 
      string currentName = wordStructList[j].name; 

      if(currentName.compare(word) == 0); 
       wordStructList[j].occurrences++; 
     } 
    } 
} 

return 0; 
} 

我希望這個問題有道理。任何人都對此有所瞭解?我也接受任何有關如何使代碼更明智/可讀的提示。由於

+0

您已經使用'std :: find_if'。也可以使用'std :: count'。 – chris

回答

7

問題是這樣的if語句後的分號:

if(currentName.compare(word) == 0); 

分號終止語句,因此下一行

wordStructList[j].occurrences++; 

不是if聲明的一部分,更多的和意志總是被執行。

+0

哇。學校男孩錯誤。謝謝弗蘭克! – AstralKinG

+0

也不需要使用if(currentName.compare(word)== 0)只要if(currentName == word) – Mike