嘿。我试图从包含单词列表的文件中将字符串读入数组。这是为了让我可以检查是否字符串是一个真正的单词是否存在于我的数组中。除了比较之外,我有一切工作。我的二进制搜索甚至传递了这个词。当它比较完全相同的两个单词时,它仍然返回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