程序在尝试打开.txt文件时崩溃

时间:2013-07-17 03:21:59

标签: c++ file-io linked-list

当我尝试运行程序时,它会在开始时崩溃。问题是我从文件输入,我可以写文件罚款。有人能解释为什么这段代码不起作用?

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

1 个答案:

答案 0 :(得分:1)

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