2014-02-24 75 views
0

我得到一個分段錯誤,我不知道爲什麼我得到這個。它在我的csv中讀取沒有問題,但在運行結束時出現分段錯誤。我已經嘗試使用Codeblocks的調試功能,並沒有太多的幫助。有人能指出我的錯誤嗎?閱讀一個csv文件得到分段錯誤

#include <iostream> 
#include <fstream> 
#include <string> 

using namespace std; 



void loadCSV(int G[][24]) { 
    ifstream csv; 
    string line; 
    csv.open("matrix.csv"); 
    if (csv.is_open()){ 
     int lineNum = 0; 
     while ((getline (csv,line)) && (lineNum!=24)){ 
      for (int pos = 0;pos<line.length();pos++){ 
       if (line.at(pos) == ','){ 
        continue; 
       } 
       //cout << line.at(pos); 
       if (line.at(pos) == '0'){ 
        G[lineNum][pos] = 0; 
        cout << lineNum << "-" << pos << "\n"; 
       } 

       else{ 
        G[lineNum][pos] = 1; 
        cout << lineNum << "-" << pos << "\n";; 
       } 
      } 
      cout << endl; 
      lineNum++; 
     } 
     cout << lineNum<< endl; 
     csv.close(); 
    } 

    else cout << "Unable to open file"; 

} 



int main(){ 
    int G[24][24]; 
    loadCSV(G); 
    cout << G[0][1]; 

    return 0; 
} 

回答

0

在將值賦給G [lineNum] [pos]之前,只需檢查'pos'和'lineNum'的值。如果它們中的任何一個大於/等於24,則該作業無效。

+0

謝謝.....我剛剛意識到我沒有考慮pos除以2 – user2079902