[英]Reading in txt file c++
我正在尝试将字典文件加载到二进制搜索树中。 我想为每个节点加载字母组合,直到形成一个单词,从而在该单词上附加一个定义。 例:
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;
}
while(!inFile.eof()){
这始终是一个错误 。
getline(inFile, words, ':'); //receives input of the words stopping at the ':' delimiter
如果输入行不包含分号,则它将吞没整行,并开始读取下一行。 和下一行。 只要找到分号就可以了。 这显然是错误的。
您需要在此处进行两项更改。
检查文件结尾是否正确
使用std::getline()
将一行文本读入std::string
,并在读取整行之后,检查读取的std::string
包含分号。
此外,您询问“我正在尝试加载不断收到inFile.fail()条件的示例文件”。 如果是这样,那么发布数百行完全无关的代码,无论是从文件中读取的内容,都毫无用处,并且可能会给您带来几分沮丧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.