2015-04-02 128 views
-1

该程序编译好,但有时它会产生分割错误。我不断得到分段错误:11错误,我不明白为什么... 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; 
} 
+0

行和列看起来混合起来。 – Grumbel 2015-04-02 20:18:50

+1

作为学生在编程中可以做出的最佳投资是花一些时间学习使用调试器并熟练掌握它。传奇程序员Donald Knuth曾经被问到他最喜欢的计算机语言是什么,他的回答是“有一个好的调试器”。 – amdn 2015-04-02 20:20:06

回答

1

你做

mo>>pracc[row][col]; 

但是你的数组定义:

double pracc[1][size]; 

row必须高于1,那么你会越过数组的边界。你可能想要

double pracc[size][1]; 
+0

否,double prac [1] [size]意味着数组2 * size的大小,prac [1] [size] = {{21},{67},... n}; etc。 – rama41222 2015-04-02 20:23:13

+0

事实上,你的循环访问pracc [row] [col],并且行高于1,所以你的数组定义是错误的。或者你可以保持数组定义相同,并执行[col] [row]。无论哪种方式工作。 – Almo 2015-04-02 20:25:55

+0

是的,谢谢!!!! – rama41222 2015-04-02 20:27:30

2

In expression pracc [row] [col];行和列范围都搞乱了。行必须小于1; 使用:: std :: array代替C风格的数组会更好。它会在相应的时刻为您提供适当的调试断言,而不是突然出现分段故障。

相关问题