打开文件后程序崩溃 [英] Program crashes after opening file

查看:105
本文介绍了打开文件后程序崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从文件中读取值到我的程序。文件已成功打开,但后来立即崩溃。我的代码有问题吗?

I need to read values from a file into my program. The file is opening successfully, but then it crashes right away. Is there something wrong with my code?

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

谢谢。

编辑:

检查后,我遇到了问题

else
    {
        lastInt->nextNode = anotherInt;
    }

因此,此代码必须有问题:

So there must be a problem with this code:

    lastInt = lastInt->nextNode;
    lastInt->intValue = fileInt;
    lastInt->nextNode = NULL;
    intInputFile >> fileInt;

因为我之前有一个cout语句,它没有工作。

Because I had a cout statement directly after it and it didn't work.

在进一步研究之后,问题出在这一行:

And after looking into it more, the problem is with this line:

     intInputFile >> fileInt;


推荐答案

假设 intList 不是 NULL ,那么您将在 lastInt-> nextNode = anotherInt; 第一次循环,而 lastInt 仍然是 NULL 导致程序崩溃(由于它遵循一个空指针) 。

Assuming intList isn't NULL, then you'll call lastInt->nextNode = anotherInt; during your first iteration of the loop while lastInt is still NULL causing the program to crash (due to it following a null pointer).

这篇关于打开文件后程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆