0

2 つの異なるテキスト ファイルを使用してプログラムを作成しようとしています。そのうちの 1 つは分析したい実際のテキストを含み、もう 1 つは単語のリストを含みます。プログラムは、リストの単語がテキストに現れたときにチェックし、それをカウントすることになっています。ここに私がこれまでに持っている(動作していない)コードがあります:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main () {

    string word1;
    string word2;
    int listHits = 0;

    ifstream data1 ("text.txt");
    if ( ! data1 ) {
    cout << "could not open file: " << "text.txt" << endl;
        exit ( EXIT_FAILURE );
  }

    ifstream data2 ("list.txt");
    if ( ! data2 ) {
    cout << "could not open file: " << "list.txt" << endl;
        exit ( EXIT_FAILURE );
  }

    while ( data1 >> word1 ) {
        while ( data2 >> word2 ) {
            if ( word1 == word2 ) {
                listHits++;
            }
        }
    }

    cout << "Your text had " << listHits << " words from the list " << endl;

    system("pause");

    return 0;
}

text.txt が含まれている場合

ここにテキストがあります。プログラムにロードされます。

と list.txt が含まれています

します

予想される結果は 3 です。ただし、テキスト ファイルに何が含まれていても、プログラムは常に答え 0 を返します。プログラムが実際にループを実行する回数をカウントすることで、ファイルを読み取ることができることを確認しました。動作します。

前もって感謝します

4

2 に答える 2

1

最初のファイルの最初の文字と2番目のファイル全体を常に比較しているように思えます。

  while ( data1 >> word1 ) {
        while ( data2 >> word2 ) { // <---- after this ends the first time, it will never enter again
            if ( word1 == word2 ) {
                listHits++;
            }
        }

2 番目のループが終了した後に data2 を「リセット」して、ファイルの先頭から再度読み取りを開始する必要があります。

 while ( data1 >> word1 ) {
        while ( data2 >> word2 ) {
            if ( word1 == word2 ) {
                listHits++;
            }    
        }
        data2.seekg (0, data2.beg);
   }
于 2013-04-05T08:28:30.577 に答える