当我尝试运行程序时,它立即崩溃。问题是我从文件输入的,我可以写到文件中。有人可以解释为什么此代码行不通吗?

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


您两次分配给pCurrentpTop看起来像一个数据成员,也许您在构造函数中表示的意思是:

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,但在读取时不检查null。 pCurrent可能是空指针。

另外,请阅读Why is iostream::eof inside a loop condition considered wrong?。您的循环应为:

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

10-04 18:49