C++处理文本文件中的分段故障11

Segmentation Fault 11 in C++ processing text file

本文关键字:分段 故障 处理 文本 文件 C++      更新时间:2023-10-16

我正试图在Mac中用C++编写一个程序来处理一个包含以下数据的文本文件(table.txt):

汤姆50 60 70.5
杰瑞80.3 65 91
标记75.2 77 92.7
Lucy 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;
}

到底是什么问题?

在C中,与大多数现代编程语言一样,数组索引从0开始,减速中的数字是大小,而不是最后一个索引。所以

double scores[2];

声明一个大小为2的数组,索引为0和1。