没有错误,但输出不正确.可能存在指针问题
No errors, but output is not right. Pointer issue possibly
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
,其中temp
是Node*
。指针只是一个对象的地址,因此您可以在输出中获得地址。
似乎您想要获取Node
包含的字符串。如果是,你想要:
cout << temp->getWord();
另一个问题是关闭文件并在循环中打印列表,这意味着它将在读取第一个单词后立即发生。您可能是想在循环之后执行,这样文件中的所有单词都可以读取。
您标记的线也有问题。使用new
关键字将动态分配对象。以后需要使用delete
删除这些对象。但是,您取消引用动态分配的对象(使用*
)并复制它,从而丢失对动态分配对象的任何引用——这是典型的内存泄漏。这里的动态分配是完全没有必要的。只需:
LinkedList list;
相关文章:
- 使用指针在存在特征库的情况下动态分配 c++ 中的矩阵
- 构造函数 (C++) 中的 char 指针参数存在问题
- C++为什么我的指针选择排序中存在分段错误?
- 迭代时将指向differents类型的指针保存在std::向量中
- 如果模板中存在成员函数指针,如何获取该指针
- 指向类成员函数的指针中存在类型转换错误
- 一个对象的两个指针.删除了一个指针,对象仍然存在
- 是否存在将长整型转换为指针有效的情况
- C ++如何创建一个即使对象被覆盖也会持续存在的指针?
- 指向派生作品的基本指针,即使派生对象不存在
- 这个危险指针示例是否因为 ABA 问题而存在缺陷?
- 指向可能不存在的对象的指针向量
- 如果存在任何循环关系,我应该假设弱指针使用吗?
- 带有功能指针的Typedef:函数不存在
- 即使在返回值之前释放后,数据仍在指针中仍然存在
- C++尝试删除不存在的指针
- 如何使用shared_ptr确保指针的存在
- 构造函数中指针到指针的默认值存在问题
- 引用的初始化无效:指针和值之间存在差异
- 没有错误,但输出不正确.可能存在指针问题