2016-02-05 37 views
0

我對C++相當陌生。我試圖打開一個文件並將其傳遞給另一個方法,以便我可以從ifstream讀取數據。這是打開文件的方法。我不明白爲什麼我使用ifstream時出現分段錯誤

int main() { 
// part 1 
    ifstream infile1("data31.txt"); 
    if (!infile1) { 
     cout << "File could not be opened." << endl; 
     return 1; 
    } 

//for each graph, find the shortest path from every node to all other nodes 
    for (;;) { 
     int data = 0; 
     GraphM G; 
     G.buildGraph(infile1); 
     if (infile1.eof()) 
      break; 

    } 

    return 0; 
}' 

然後,我有另一種方法,是在一個名爲GraphM另一個類,我已經實現了這種方式:

void GraphM::buildGraph(ifstream& infile1) { 
    int data = 0; 
    infile1 >> data; 
    cout << "data = " << data << endl; 
} 

但是當我嘗試讀取數字存儲到一個數據變量,我出現分段錯誤。任何人都可以幫我弄清楚什麼是錯的?

在此先感謝。

+0

考慮(1)'outputing錯誤消息時,使用'的std :: cerr'和'退出。 – PhotometricStereo

回答

1

我無法解釋分段故障,但使用infile.eof()來打破並不是一個好策略。進一步的細節見Why is iostream::eof inside a loop condition considered wrong?

我建議使用:

int main() { 

    ifstream infile1("data31.txt"); 
    if (!infile1) { 
     cout << "File could not be opened." << endl; 
     return 1; 
    } 

    // Continue reading as long as the stream is valid. 
    for (; infile1 ;) { 
     GraphM G; 
     G.buildGraph(infile1); 
    } 

    return 0; 
} 

void GraphM::buildGraph(ifstream& infile1) { 
    int data = 0; 
    if (infile1 >> data) 
    { 
     // Data extraction was successful. 
     cout << "data = " << data << endl; 
    } 
} 
相關問題