Program Crashing while trying to open a .txt file

风流意气都作罢 提交于 2019-12-25 05:26:14

问题


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

回答1:


pCurrent = pTop; Why do you assign this here? This makes pCurrent null pointer. Please remove or fix.

I'm confused with your code:

pCurrent = new StringListNode; // Allocate new memory and point at it
pCurrent = pTop; // Make pCurrent point at same thing as 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

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

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

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


来源:https://stackoverflow.com/questions/17690533/program-crashing-while-trying-to-open-a-txt-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!