我需要将文件中的值读取到我的程序中。文件打开成功,但随后立即崩溃。我的代码有问题吗?
void createList(intNode*& intList)
{
intNode* lastInt; //points to last integer in file
lastInt = NULL;
int fileInt; //int read from input file
ifstream intInputFile;
intInputFile.open("intInput.txt");
if (intInputFile.is_open())
{
cout << "intInput.txt open successful" << endl;
}
else
{
cout << "intInput.txt open unsuccessful" << endl;
}
intInputFile >> fileInt;
while(!intInputFile.eof())
{
intNode* anotherInt;
anotherInt = new intNode;
if(intList==NULL)
{
intList = anotherInt;
lastInt = anotherInt;
}
else
{
lastInt->nextNode = anotherInt;
}
lastInt = lastInt->nextNode;
lastInt->intValue = fileInt;
lastInt->nextNode = NULL;
intInputFile >> fileInt;
}
intInputFile.close();
cout << "List created from input file" << endl;
}
Thanks.
Edit:
检查后发现有问题
else
{
lastInt->nextNode = anotherInt;
}
所以这段代码肯定有问题:
lastInt = lastInt->nextNode;
lastInt->intValue = fileInt;
lastInt->nextNode = NULL;
intInputFile >> fileInt;
因为我后面直接有一个cout语句,但它不起作用。
经过更多研究后,问题出在这一行:
intInputFile >> fileInt;
假设intList
isn't NULL
,然后你会打电话lastInt->nextNode = anotherInt;
在循环的第一次迭代期间lastInt
还是NULL
导致程序崩溃(由于它遵循空指针)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)