2016-05-08 14 views
0

辞書ファイルをバイナリ検索ツリーに読み込もうとしています。私はそれが単語を形成するまで、その単語に定義を付けるまで、各ノードに文字の組み合わせをロードしたいと思います。例:txtファイルで読む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; 
} 
+1

こんにちは!私はこれがかなりのコードであることを認めなければなりません。これは本当に**本当に**最小の**不正確な例ですか?私はすべての "入力処理"ロジックは機能をテストするために全く必要ではないと思います。エラーを再現するのに必要な最小限にあなたの例を減らしてください。 –

答えて

0
 while(!inFile.eof()){ 

このis always a bug:ここ

は、私は私の問題を引き起こしている可能性を考える二つの機能があります。

  getline(inFile, words, ':'); //receives input of the words stopping at the ':' delimiter 

入力行にセミコロンが含まれていない場合は、行全体を呑み込み、次の行の読み込みを開始します。そして次の行。セミコロンを見つけるのにかかる時間です。これは明らかに間違っています。

ここでは2つの変更が必要です。

  • ファイルの終わりのためのチェック、適切

  • 使用std::getline()std::stringにテキストの一行を読み、行全体が読み込まれた後、読み取りstd::stringにセミコロンが含まれているかどうかをチェックします。

さらに、あなたは「私はinFile.fail()条件を受信し続けるサンプルファイルをロードしようとしています」尋ねました。そうであれば、何もしなくても何百というファイルを読み込んで何百ものコードを投稿することは、まったく目的を果たさず、おそらくいくつかのダウンワードを得ることになります。

+0

私の入力行にはすべてコロンが含まれています。ご返信ありがとうございます。私はループ内のeof()バグの状況を知りませんでした。私がDictionary.cpp全体を投稿した唯一の理由は、エラーがinsertTrie関数内にあるかどうかわからず、コード全体のスコープを持つのに役立つかもしれないと考えたためです。もう一度あなたに感謝します。 –

関連する問題