2015-11-18 41 views
1

我試圖寫在C++編程中的Mac來處理一個文本文件(table.txt)具有以下數據:分割故障11在C++中處理文本文件

湯姆50 60 70.5
傑裏80.3 65 91
馬克75.2 92.7 77
露西100 87.6 93

不過,我從終端運行它得到的是這個,有段故障11:

湯姆50 60 70.5
傑裏80.3 65 91
馬克75.2 77 92.7
分段故障:11

這裏是我的程序:

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

using namespace std; 

struct StudentList { 
    string name; 
    double scores[2]; 
}; 

int main() { 

    ifstream marks; 
    marks.open("table.txt"); 

    StudentList Student[50]; 

    int index = 0; 

    string text; 
    if (marks.fail()) { 
     cout << "fail open" << endl; 
    } 

    while (marks >> text) { 
     cout << text << " "; 
     Student[index].name = text; 
     marks >> Student[index].scores[0]; 
     cout << Student[index].scores[0] << " "; 

     marks >> Student[index].scores[1]; 
     cout << Student[index].scores[1] << " "; 

     marks >> Student[index].scores[2]; 
     cout << Student[index].scores[2] << " "; 

     cout << endl; 
     index++; 
     cout << index << endl; 
    } 

    marks.close(); 

    return 0; 
} 

到底是什麼問題?

+2

你只分配空間2分:'雙摺線,[2];'但嘗試讀取3:'標記> > Student [index] .scores [2];'訪問數組越界是未定義的行爲。 –

回答

0

在C中,與大多數現代編程語言一樣,數組索引從0開始,減速中的數字是大小,而不是最後一個索引。所以

double scores[2]; 

聲明大小爲2的數組,使用索引0和1

+0

是的,這是一個愚蠢的錯誤。非常感謝你! – Michelle

+0

@Michelle通常的感謝方式是upvote/accept – baruch