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

第二条 1

第 3 条 2

第 4 条 3

第 5 条 4

在第 1 部分中的“cout”之后,不再打印。

4

1 回答 1

0

从这里开始:

WORDS *current = new WORDS();

当不需要全局变量时,您可以使用全局变量,但让它过去。

int main(){
  ...
  current = head;

您刚刚忘记了分配的内存current = new WORDS()——这称为内存泄漏——但让它过去吧。

current = head;
while (current->name != "\0") {;
  cout << current->name << "  " << current->number_of_words << '\n';
  current = current->next;
}

name您从未使用“\0”的元素终止列表。列表中的最后一个元素有一个未初始化的next成员(几乎可以肯定)不指向有效WORDS对象。因此,当您设置current为该值并取消引用它(使用current->name)时,您会得到未定义的行为。

有几种方法可以防止这种情况。我建议编写一个默认WORDS设置next为 null 的构造函数,然后对其进行测试。

于 2013-05-26T13:00:14.257 回答