0

なぜこれが機能しないのか、私の人生では理解できません。ファイルから単語のリストの頻度チェックを行う必要があり、それらを読み取るときに、現在の単語を文字列配列の要素と照合してチェックしようとしています。それを追加します。コードは次のとおりです。

fin.open(finFile, fstream::in);

if(fin.is_open()) {
    int wordArrSize;
    while(!fin.eof()) {
        char buffer[49]; //Max number chars of any given word in the file
        wordArrSize = words.length();

        fin >> buffer;

        if(wordArrSize == 0) words.push_back(buffer);

        for(int i = 0; i < wordArrSize; i++) { //Check the read-in word against the array
            if(strcmp(words.at(i), buffer) != 0) { //If not equal, add to array
                words.push_back(buffer);
                break;
            }
        }



        totNumWords++; //Keeps track of the total number of words in the file
    }
    fin.close();

これは学校のプロジェクト用です。コンテナー クラスを使用することは許可されていないため、char** 配列の展開、要素のプッシュ バックとポップアウトなどを処理する構造を構築しました。

4

2 に答える 2

1

あなたのコードwords.push_back(buffer);はforループの外に出るべきだと思います。フラグを設定して、forループ内の配列にバッファーが見つかったかどうかを確認し、フラグに従って、forループ外の配列にバッファーを追加します。

于 2013-02-11T07:25:43.397 に答える
1
for(int i = 0; i < wordArrSize; i++) { //this part is just fine
    if(strcmp(words.at(i), buffer) != 0) { //here lies the problem
         words.push_back(buffer);
         break;
    }
}

現在の単語が配列内ifの th 単語と一致しないたびに、ステートメントを入力します。iそのため、ほとんどの場合、ループに入るのは最初の繰り返しになります。これは、サイクルの開始時に (文字列リスト内の最初の単語でバッファに一致しない)、バッファを文字列リストに追加し、サイクルを中断することを意味します。

すべきことは、配列全体のチェックを終了してwordsから、バッファーを配列に追加することです。したがって、次のようなものが必要です。

bool bufferIsInTheArray = false;//assume that the buffered word is not in the array.
for(int i = 0; i < wordArrSize; i++) { 
    if(strcmp(words.at(i), buffer) == 0) {
         //if we found a MATCH, we set the flag to true
         //and break the cycle (because since we found a match already
         //there is no point to continue checking)
         bufferIsInTheArray = true;
         break;
    }
//if the flag is false here, that means we did not find a match in the array, and 
//should add the buffer to it.
if( bufferIsInTheArray == false )
    words.push_back(buffer);
}
于 2013-02-11T07:34:03.437 に答える