4

ファイルからプログラムに値を読み込む必要があります。ファイルは正常に開いていますが、すぐにクラッシュします。私のコードに何か問題がありますか?

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

したがって、このコードには問題があるはずです。

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

その直後に cout ステートメントがあり、機能しなかったためです。

さらに調べてみると、問題は次の行にあります。

     intInputFile >> fileInt;
4

2 に答える 2

3

でないと仮定するとintList、ループの最初の反復中にNULL呼び出しますが、まだプログラムがクラッシュします (null ポインターに続くため)。lastInt->nextNode = anotherInt;lastIntNULL

于 2012-12-19T01:13:26.917 に答える
1

intInput.txtファイルが適切にフォーマットされていると仮定すると、intInputFile >> fileInt;行はファイルから最初の整数を正しく読み取る必要があるため、に問題があるはずifstreamです。のis_openメンバー関数はifstream、ストリームにファイルが関連付けられているかどうかのみを通知します。ファイルを開く際に問題が発生したかどうかは、必ずしもわかりません。関数で確認できgoodます。例えば:

if (intInputFile.good()) 
    cout << "intInputFile is good" << endl;
else 
    cout << "intInputFile is not good" << endl;

strerror(errno)システムによっては、次の方法を使用してエラーの原因を特定できる場合があります。

#include <cstring>
#include <cerrno>

...

if (!intInputFile.good())
    cout << strerror(errno) << endl;

これは私にとってはうまくいきますが、どこでもうまくいくとは限らないので、詳細についてはこの質問を参照してください。

于 2012-12-19T02:31:15.290 に答える