0

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();
 }
GiBiT 09
  • 211
  • 6
  • 18

1 Answers1

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;
}
Community
  • 1
  • 1
Jesse Good
  • 46,179
  • 14
  • 109
  • 158
  • Awesome, thank you that fixed my crashing issue, but it is not displaying the text from the file. – GiBiT 09 Jul 17 '13 at 03:31
  • Please remove `pCurrent = pTop;`, why do you do this assignment? – Jesse Good Jul 17 '13 at 03:32
  • ahh, That was frustrating me beyond compare, It works now. Thank you so much. – GiBiT 09 Jul 17 '13 at 03:46
  • @GiBiT09: Does it read the whole file? It looks like it only reads from the file one time. Perhaps you need to build the linked list by allocating new memory in the loop, but I will leave that for you to figure out. – Jesse Good Jul 17 '13 at 03:59
  • Yea it only displays the first one in the file. So your if i make a pointer inside the loop like StringListNode * pNew; pNew = pNew->pNext;?? – GiBiT 09 Jul 17 '13 at 04:07
  • Ah just tried that, that makes it display only the last item in the list. – GiBiT 09 Jul 17 '13 at 04:08
  • @GiBiT09: No, you probably want ` pCurrent->pNext = new StringListNode; pCurrent = pCurrent->pNext;`. However, you should learn about how pointers work better. – Jesse Good Jul 17 '13 at 07:01