2011-04-26 86 views
1

嘿。我試圖從包含單詞列表的文件中將字符串讀入數組。這是爲了讓我可以檢查是否字符串是一個真正的單詞是否存在於我的數組中。除了比較之外,我有一切工作。我的二進制搜索甚至傳遞了這個詞。當它比較完全相同的兩個單詞時,它仍然返回false。我認爲這個問題可能是因爲我正在拉字,因爲string.compare()函數正常工作正常。這是代碼。我會喜歡一些幫助。謝謝。從文件讀取字符串到數組

ifstream dictFile; 
    dictFile.open("dictionary.txt"); 
    if (!dictFile) // testing if file open 
    { 
     cout << "Error opening dictionary file" << endl; 
    } 
    int index = 0; // dictionary must progress start at line 1 
    while(!dictFile.eof()) 
    { 
     getline(dictFile,dictionary[index]); 
     index++; 
    } 
    dictFile.close(); 

有沒有什麼是完全錯誤的,我怎麼要這麼做?

編輯 這裏是比較代碼以及

bool database::is_word(string word) 
{ 
    int ii; 
    int comp; 
    int min = 0; 
    int max = dictSize; 
    // this will go into the dictionary and look for the word 
    // it uses a binary search pattern 
while (min<=max) 
    { 
     ii = (min+max)/2; 
     comp = word.compare(dictionary[ii]); 
     cout <<dictionary[ii]; 
     if (comp==0) 
    { 
     cout << word<< " is a word!" << endl; 
     return 1; 
    } 
     else if (comp < 0) 
    { 
     max = ii-1; 
    } 
     else 
    { 
     min = ii+1; 
     } 
     } 
cout << word << " is NOT a word!" << endl; 
    return 0; 
} 
+0

Getline是否檢索該單詞以及該行末尾的\ n(返回)?如果是這樣,比較可以認爲這些詞是不同的,因爲它會像「詞」!=「詞\ n」loook。只是一個想法。 – Genzume 2011-04-26 16:34:54

+0

@Tyler getline()刪除換行符。 – 2011-04-26 16:37:54

+0

@unapersson好的,很高興知道。謝謝。 – Genzume 2011-04-26 16:39:00

回答

1

不是EOF()函數再次!你想:

while(getline(dictFile,dictionary[index])) { 
    index++; 
} 

(假設dictionary是什麼明智的,它可能不是),因爲EOF()不預測,如果下一個讀會工作。

哪裏有人從哪裏拿起eof()的這個用法?這就像一種疾病!

+0

看到它的地方...我會立即做一個精神上的筆記,不要再次使用它。但是,此修復程序會產生相同的錯誤。 – Rusty 2011-04-26 16:44:22

+1

我更喜歡把它寫成:'for(string line; getline(input,line);){...}'因爲它比較習慣,可以對行內容進行後期處理,並且在各種容器類型中是統一的。 – 2011-04-26 17:53:10

+0

@Andre我不能說我認爲它是慣用的 - 我期望for循環從一個已知值循環到另一個,而不是不確定。 – 2011-04-26 18:18:03

0

這就是我如何做整個程序,如果我的目標是簡潔而不是表現。

// read the dictionary 

vector<string> dictionary; 
{ 
    ifstream dictionary_file("dictionary.txt"); 
    istream_iterator<string> begin(dictionary_file); 
    istream_iterator<string> end; 
    while(begin != end) 
    dictionary.push_back(*begin++); 
    sort(dictionary.begin(), dictionary.end()); 
} 

// read the input file and test against the dictionary 

{ 
    ifstream input_file("input.txt"); 
    istream_iterator<string> begin(input_file); 
    istream_iterator<string> end; 
    while(begin != end) 
    { 
    string input = *begin++; 
    vector<string>::iterator it = lower_bound(dictionary.begin(), dictionary.end(), input); 
    if(it != dictionary.end() && *it == input) 
     cout << input << " found!" << endl; 
    else 
     cout << input << " not found!" << endl; 
    } 
} 
+0

使用'std :: set'可能會給你更好的性能,使意圖更清晰,並簡化它:'dictionary.find(word)!= dictionary.end()'比使用lower_bound ()'在矢量上! – 2011-04-26 17:57:16

+1

你說得對,std :: set會更清晰,但你錯了,它會有更好的表現。 std :: set和一個已排序的std :: vector在搜索一個項目時應該具有完全相同的性能。 – bmcnett 2011-04-26 18:08:35