我不断得到分段错误:11错误,我不明白为什么... C++
问题描述:
该程序编译好,但有时它会产生分割错误。我不断得到分段错误: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;
}
答
你做
mo>>pracc[row][col];
但是你的数组定义:
double pracc[1][size];
和row
必须高于1,那么你会越过数组的边界。你可能想要
double pracc[size][1];
答
In expression pracc [row] [col];行和列范围都搞乱了。行必须小于1; 使用:: std :: array代替C风格的数组会更好。它会在相应的时刻为您提供适当的调试断言,而不是突然出现分段故障。
行和列看起来混合起来。 – Grumbel 2015-04-02 20:18:50
作为学生在编程中可以做出的最佳投资是花一些时间学习使用调试器并熟练掌握它。传奇程序员Donald Knuth曾经被问到他最喜欢的计算机语言是什么,他的回答是“有一个好的调试器”。 – amdn 2015-04-02 20:20:06