我写了一个代码来获取目录中的文本文件名,获取文章的长度,即文章中的单词数,这两个步骤似乎运行良好,输出是我想要的。这里我使用链表来存储所有的文件名、长度等。但是当我想处理存储在这些结构中的结果时。例如,获取长度在 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
第二条 1
第 3 条 2
第 4 条 3
第 5 条 4
在第 1 部分中的“cout”之后,不再打印。