[英]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.