2012-12-19 144 views
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; 
    } 

所以必須有與此代碼的一個問題一個問題:因爲我直接了COUT聲明

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

之後它並沒有工作。

而且尋找到它經過,問題是這一行:

 intInputFile >> fileInt; 
+0

你可以添加更多的cout來找到代碼崩潰的確切位置嗎? – Josay

+4

如果它崩潰了,那麼是的,你的程序有問題。 –

+0

好的,我現在就試試。 –

回答

3

假設intListNULL,那麼您會在循環的第一次迭代中調用lastInt->nextNode = anotherInt;lastInt仍然NULL導致程序崩潰(由於它遵循空指針)。

+0

由於聲明我的程序崩潰了:intInputFile >> fileInt; –

+0

這與您編輯的帖子「我之後有問題」不匹配。你應該編輯你的問題。同時嘗試在該線上設置斷點,並在到達時驗證您的數據流是否正常。 – Mario

+0

好的,我做到了。我事先知道一切都很好,我認爲問題出自我最初的價值觀。我用5個整數創建了一個文件,當我的程序嘗試讀取下一個整數時,它崩潰了。我把每個整數值放在一個單獨的行中,是嗎? –

1

假設intInput.txt文件格式正確,您的intInputFile >> fileInt;行應該從中讀取第一個整數就好了,所以ifstream必須有一些問題。 ifstreamis_open成員函數只會告訴您該流是否有與之關聯的文件。它不一定告訴你打開文件是否有問題。你可以用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; 

這對我的作品,但看this question的更多信息它可能無處不在。