我試圖寫在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];'但嘗試讀取3:'標記> > Student [index] .scores [2];'訪問數組越界是未定義的行爲。 –