本文介绍了尝试打开.txt文件时出现程序崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试运行我的程序时,它崩溃的开始。问题是我从文件输入,我可以写文件很好。有人可以解释为什么这个代码不工作?

When I try to run my program it crashes right of the start. The problem is my input from file, I can write to the file fine. Can someone explain why this code wouldn't work??

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();
}

此输出到文件可以正常工作。我以为我会包括它。

This Output to the file works fine. I thought I would just include it.

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 = pTop; Why do you assign this here? This makes pCurrent null pointer. Please remove or fix.

我与您的验证码混淆:

pCurrent = new StringListNode; // Allocate new memory and point at it
pCurrent = pTop; // Make pCurrent point at same thing as pTop

您分配给 pCurrent 两次。 pTop 看起来像一个数据成员,也许你的意思是在构造函数:

You assign to pCurrent twice. pTop looks like a data member, perhaps you meant in constructor:

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

and in destructor remove pCurrent = new StringListNode; because it does not do anything.

输出时,检查 pCurrent!= 0 ,但是在阅读时不检查null。可能 pCurrent 是空指针。

When outputting, you check pCurrent != 0, but you do not check for null when reading. Probably pCurrent is null pointer.

另请参阅为什么iostream :: eof在循环条件内被认为是错误?您的回圈应为:

Also, please read Why is iostream::eof inside a loop condition considered wrong?. Your loop should be:

while(pCurrent && (in >> pCurrent->data)) 
{
   pCurrent = pCurrent->pNext;
}

这篇关于尝试打开.txt文件时出现程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!