0

ディレクトリ内のテキスト ファイル名を取得し、記事の長さ (記事内の単語数) を取得するコードを作成しました。ここでは、すべてのファイル名、長さなどを格納するためにリンク リストを使用しました。しかし、これらの構造に格納された結果を処理したい場合。たとえば、長さが 0 ~ 3 の範囲内にあるテキスト ファイルの数を取得したり、すべての記事の最大長を取得したりします。対応するコードの出力はありません。問題が何であるかを理解するのを手伝ってくれませんか? これが私のコードです。C++ で書きました。IDE は Xcode です。

///////////////////////////////////////////////////////
//part 1 works correctly, part 2 and 3 is not working//
///////////////////////////////////////////////////////

#include <iostream>
#include <string>

using namespace std;

struct WORDS{
int number_of_words;
string name;;
WORDS *next;
};
WORDS *head = new WORDS();
WORDS *current = new WORDS();

int main(){
string article[] = {"article1", "article2", "article3", "article4", "article5"};
head->name=article[0];
head->number_of_words = 0;
current = head;
for (int i = 1; i < 5; i ++) {
    current->next = new WORDS();
    current->next->name = article[i];
    current->next->number_of_words = i;
    current = current->next;
}

//part 1: print all the file names and their lengths
cout << "length of article (in words): \n";
current = head;
while (current->name != "\0") {;
    cout << current->name << "  " << current->number_of_words << '\n';
    current = current->next;
}

//part 2: find out the number of articles whose lengths are within range 0-3
current = head;
unsigned long count = 0;
while (current->name != "\0") {
    if (current->number_of_words > 0 && current->number_of_words <= 3){
        count ++;
        cout << "Articles with length from 0 to 3 are: " << '\n';
        cout << current->name << "  " << current->number_of_words << '\n';
    }
    current = current->next;
}
cout << "Number of articles within range is: " << count << '\n';

//part 3:find out the maximum length of all the articles
WORDS *max = new WORDS();
current = head;
max = head;

while (current->name != "\0") {
    if (current->next->number_of_words > max->number_of_words) {
        max = current->next;
    }
    current = current->next;
}

cout << "maximum length of all articles is: " << max->number_of_words << '\n';

return 0;
}

出力は次のようになります: (申し訳ありませんが、まだ画像を投稿できません) 記事の長さ (言葉で):

記事1 0

記事2 1

記事3 2

記事4 3

記事5 4

パート 1 の「cout」以降は印刷されません。

4

1 に答える 1