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;
}
但是當我嘗試讀取數字存儲到一個數據變量,我出現分段錯誤。任何人都可以幫我弄清楚什麼是錯的?
在此先感謝。
考慮(1)'outputing錯誤消息時,使用'的std :: cerr'和'退出。 – PhotometricStereo