我不断得到分段错误:11个错误,我无法弄清楚为什么...... c ++

时间:2015-04-02 20:15:23

标签: c++

此程序编译正常,但有时会产生分段错误。

该程序应该让用户输入学生姓名,理论获得的分数(70%)和实际论文(30%)。这些数据应保存到文件中,最后程序应显示/存储学生的姓名和标记。

#include <iostream>
#include <fstream>

void disp(int);
using namespace std;
void stunames(int n) {

    int count = 0;
    string names;

    cout << "Input student names :" << endl;
    ofstream na("names.txt");

    while( count <= n ) {

        getline(cin,names);
        na << names << endl;
        count++;
    }
    na.close();
}
void theomarks(int size) {

    double marks;
    int count = 0;
    ofstream tho("T.txt");

    while( count < size ) {
        cin >> marks;
        if((marks > 100) ||(marks < 0)){
            cout << "Invalid marks, Re-enter" << endl;
            count = count-1;
        }
        else
            tho << marks*.7 << endl;
        count++;
    }

    tho.close();

}
void pracmarks(int size) {

    ofstream pr("P.txt");
    double marks;
    int count = 0;

    while( count < size ) {

        cin >> marks;
        if((marks > 100) ||(marks < 0)){
            cout << "Invalid marks, Re-enter" << endl;
            count = count-1;
        }
        else
            pr << marks*.3 << endl;
        count++;
    }
    pr.close();
}


void calc(int size) {

    ifstream na("names.txt");
    ifstream readr("T.txt");
    ifstream mo("P.txt");
    string x;
    double pracc[1][size];
    double theory[1][size];
    cout << "NAME\t\tMARKS" << endl;

    for(int row = 0; row < size; row++) {

        for(int col = 0; col < 1; col++) {

            mo >> pracc[row][col];
            readr >> theory[row][col];
            na >> x;
            cout << x << "\t\t" << theory[row][col]+pracc[row][col];
        }
        cout << endl;
    }
    readr.close();
    mo.close(); 
    na.close();
}

int main() {

    int no;     
    cout << "Input the number of student: " << endl;
    cin >> no;
    stunames(no);
    cout << "Input Theory Paper Marks" << endl;
    theomarks(no);
    cout << "Input practical Paper Marks" << endl;
    pracmarks(no);
    calc(no);

    return 0;
}

2 个答案:

答案 0 :(得分:2)

表达式pracc [row] [col]; row和col范围混乱了。行必须小于1; 最好使用:: std :: array而不是C风格的数组。它会在相应的时刻给你一个适当的调试断言,而不是突然的分段错误。

答案 1 :(得分:1)

你正在做

mo>>pracc[row][col];

但你的数组是定义的:

double pracc[1][size];

row超过1.因此,您将越过数组的边界。你可能想要

double pracc[size][1];