问题
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