我正在尝试将字典文件加载到二叉搜索树中。我想用字母组合加载每个节点,直到它形成一个单词,从而将定义附加到该单词。例如:
C:
Ca:
Cat: a mammal. Closely related to a Liger.
目前,我正在尝试加载示例文件,并且我一直在接收我的inFile.fail()条件。非常感谢任何帮助,建议和/或代码审查。
以下是我认为可能导致我的问题的两个功能:
bool Dictionary::insertTrie(string word, string def)
{
Node* newNode = createTrie();
string tempW;
bool retVar;
bool found = searchNode(root, word);
if(found)
retVar = false;
while(!found){
newNode->word = word;
newNode->definition = def;
insert(root, newNode);
retVar = true;
}
/*while(!found){
for(int i = 0; i < word.length(); i++){ //loop to iterate through the string
for(int j = 0; j < ALPHABET_SIZE; j++){ //loop to iterate the nodes
tempW += word[i];
newNode->word = word;
newNode->definition = def;
newNode = newNode->next[j];
}
retVar = true;
}*/
return retVar;
}
bool Dictionary::loadDictionary(string fileName)
{
fstream inFile;
string file;
string words;
string defs;
string tempW;
bool retVar;
inFile.open(fileName, ios::in); // opens
cout << "\nLoading Dictionary...\n";
if(inFile.fail()){
retVar = false;
cout << "ERROR: Dictionary file failed to load. Please try again.\n";
}
else{
while(!inFile.eof()){ //loop reads in words and definitions until the end of file bit is received
for(int i = 0; i < words.length(); i++){
getline(inFile, words, ':'); //receives input of the words stopping at the ':' delimiter
tempW += words[i];
getline(inFile, defs, '\n'); //receives input of the defs stopping at the '\n' delimiter
insertTrie(tempW, defs); //inserts the words and the definition
}
}
retVar = true;
}
inFile.close(); //closes the file
return retVar;
}
答案 0 :(得分:0)
while(!inFile.eof()){
getline(inFile, words, ':'); //receives input of the words stopping at the ':' delimiter
如果输入行不包含分号,则会吞下整行,并开始读取下一行。而下一行。只要找到分号就可以了。这显然是错误的。
您需要在此处进行两项更改。
正确检查文件结尾
使用std::getline()
将单行文本读入std::string
,读完整行后,检查读取std::string
是否包含分号。
此外,您问“我正在尝试加载我一直收到inFile.fail()条件的示例文件”。如果是这样的话,那么发布数百行完全无关的代码,无论如何,从文件中读取,绝对没有任何目的,并且可能会为你赢得一些赞成票。