没有错误,但输出不正确.可能存在指针问题

No errors, but output is not right. Pointer issue possibly

本文关键字:存在 指针 问题 不正确 有错误 输出      更新时间:2023-10-16

Im从文件中读取字符串,并按字母顺序(C++)将它们插入到LinkedList中。我已经创建了节点和列表类,但它们有问题。我在Java中完成了这项工作,它100%正常工作,没有任何问题。这让我相信,我一定在某个地方把指针搞砸了。这也是我第二次使用"->"符号。所以我可能在某个地方用错了。非常感谢一些有用的提示。提前谢谢。

//NODE CLASS
#include <string>
#include <iostream> 
using namespace std;
class Node {
    string word;
    int count;
    Node* next;
    public:
    Node (string aWord) {
        word = aWord;
        count = 1;
    }
    Node (string aWord, Node* theNext) {
        word = aWord;
        next = theNext;
    }
    void increaseCount() {
        count++;
    }
    string getWord() {
        return word;
    }
    int getCount() {
        return count;
    }
    Node* getNext() {
        return next;
    }
    void setNext(Node* theNext) {
        next = theNext;
    }
};
//LIST CLASS
#include<iostream>
using namespace std;
class LinkedList {
    Node* head;
    public:
    LinkedList() {
        head = new Node(" ");
    }
    void insert(string word) {
        Node* temp = head;
        Node* previous = head;
    while (temp != NULL && temp->getWord() < word) {
        previous = temp;
        temp = temp->getNext();
    }
    if (temp == NULL) {
        Node* node= new Node(word);
        previous-> setNext(node);
    } else {
        if (temp-> getWord() == word) {
            temp->increaseCount();
        } else if (temp->getWord() > word) {
            Node* node = new Node(word, temp);
            previous->setNext(node);
        }
      }
    }
    void print() {
        Node* temp = head->getNext();
        while (temp != NULL) {
            cout<< temp;
            temp=temp->getNext();
        }
    }
};
//MAIN
#include <iostream>
#include <iostream>
#include <fstream>
#include "Node.h"
#include "LinkedList.h"
using namespace std;
int main(int argc, const char * argv[]) {
        ifstream inFile("WordsStatisticData1.txt");
        if (!inFile.is_open())
        cout<< "Could not open the file"<< endl;
        else {
            string readData;
            LinkedList list = *new LinkedList(); //Probably a problem here
            while (inFile >> readData) {
                list.insert(readData);
                inFile.close();
                list.print();
            }
        }
    }

我可能也在宣称主要内部的事情是完全错误的。我的输出看起来像是带有随机字符的地址"0x"。

您正在打印temp,其中tempNode*。指针只是一个对象的地址,因此您可以在输出中获得地址。

似乎您想要获取Node包含的字符串。如果是,你想要:

cout << temp->getWord();

另一个问题是关闭文件并在循环中打印列表,这意味着它将在读取第一个单词后立即发生。您可能是想在循环之后执行,这样文件中的所有单词都可以读取。

您标记的线也有问题。使用new关键字将动态分配对象。以后需要使用delete删除这些对象。但是,您取消引用动态分配的对象(使用*)并复制它,从而丢失对动态分配对象的任何引用——这是典型的内存泄漏。这里的动态分配是完全没有必要的。只需:

LinkedList list;