程序在试图打开.txt文件时崩溃
问题描述:
当我尝试运行我的程序时,它崩溃了开始的权利。问题是我从文件输入,我可以写入文件罚款。有人可以解释为什么这段代码不起作用吗?程序在试图打开.txt文件时崩溃
StringList::StringList()
{
pTop=NULL;
pBottom=NULL;
ifstream in;
in.open("read.txt");
StringListNode * pCurrent;
pCurrent = new StringListNode;
pCurrent = pTop;
while(!in.eof()) //reads it till the end of file
{
in >> pCurrent->data;
pCurrent = pCurrent->pNext;
}
in.close();
}
此输出到文件工作正常。我想我会包括它。
StringList::~StringList()
{
ofstream out;
out.open("read.txt");
StringListNode * pCurrent;
pCurrent = new StringListNode;
pCurrent = pTop;
while(pCurrent != 0)
{
out << pCurrent->data << endl;
pCurrent = pCurrent->pNext;
}
out.close();
}
答
pCurrent = pTop;
为什么在这里指定这个?这使得pCurrent
空指针。请删除或修复。
我很困惑你的代码:
pCurrent = new StringListNode; // Allocate new memory and point at it
pCurrent = pTop; // Make pCurrent point at same thing as pTop
分配给pCurrent
两次。 pTop
看起来像一个数据成员,也许你在构造函数中的意思是:
pCurrent = new StringListNode; // Allocate new memory and point at it
pCurrent->pNext = nullptr; // Assign null to next pointer
pTop = pCurrent; // Make pTop point at new memory
和析构函数删除pCurrent = new StringListNode;
因为它没有做任何事情。
输出时,您检查pCurrent != 0
,但您在阅读时不检查空值。可能pCurrent
是空指针。请参阅Why is iostream::eof inside a loop condition considered wrong?。你的循环应该是:
while(pCurrent && (in >> pCurrent->data))
{
pCurrent = pCurrent->pNext;
}
真棒,谢谢你修复了我的崩溃问题,但它不显示文件中的文本。 –
请删除'pCurrent = pTop;',你为什么要做这个任务? –
啊,这让我感到沮丧,无法比拟,它现在起作用。非常感谢。 –