嘿。我試圖從包含單詞列表的文件中將字符串讀入數組。這是爲了讓我可以檢查是否字符串是一個真正的單詞是否存在於我的數組中。除了比較之外,我有一切工作。我的二進制搜索甚至傳遞了這個詞。當它比較完全相同的兩個單詞時,它仍然返回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;
}
Getline是否檢索該單詞以及該行末尾的\ n(返回)?如果是這樣,比較可以認爲這些詞是不同的,因爲它會像「詞」!=「詞\ n」loook。只是一個想法。 – Genzume 2011-04-26 16:34:54
@Tyler getline()刪除換行符。 – 2011-04-26 16:37:54
@unapersson好的,很高興知道。謝謝。 – Genzume 2011-04-26 16:39:00