[英]I keep getting segmentation fault :11 errors and i can't figure out why… 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;
}
在表達式中pracc [row] [col]; 行和列的范圍搞砸了。 行必須小於1; 最好使用:: std :: array而不是C樣式的數組。 它會在相應的時刻為您提供適當的調試聲明,而不是突然的分段錯誤。
你在做
mo>>pracc[row][col];
但是您的數組已定義:
double pracc[1][size];
並且row
超過1。因此,您將越過數組的邊界。 你可能想要
double pracc[size][1];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.