我的程序一行一行地讀取一個文本文件,以獲得關於一羣捐獻者的信息。它使用一系列結構來存儲信息(名稱,捐贈金額)。文本文件的第一行是貢獻者的數量。從那時起,代表捐贈的名稱和價值。例如:我的程序給了我一個分段錯誤(C++)
3
Kyle Butler
10340
James Wright
5006
John Smith
10000
然後,如果他們的捐款爲10,000或更多,他們的名字和捐款值輸出到標題下的屏幕「大主顧」,否則,它出現在標題下的「食客」
問題是,當我運行程序時,它給了我一個分段錯誤,沒有證據顯示程序輸出任何東西到屏幕上。有人可以告訴我這裏發生了什麼嗎?我對這門語言很陌生。
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
#include <cctype>
#include <cstdlib>
using namespace std;
struct contribute {
char Name[100];
int contribution;
};
int main()
{
char tempstore[100];
int linecount=1;
int pointerindex=0;
ifstream inputfile("myfile.txt");
if (!inputfile.is_open()){
cout << "Error opening file";
}
inputfile.getline(tempstore, 20);
int contributors = atoi(tempstore);
contribute carray[contributors];
while (!inputfile.eof()){
if(linecount ==1){
linecount++;
continue;
}
inputfile.getline(tempstore, 20);
if ((linecount % 2) == 0){
strcpy((carray[pointerindex]).Name, tempstore);
}
else {
(carray[pointerindex]).contribution = atoi(tempstore);
}
++linecount;
++pointerindex;
}
cout << "\n#####--#-Grand Patrons-#--#####\n";
for (int i=0; i<contributors; i++){
if (carray[i].contribution >= 10000){
cout << "Name: " << carray[i].Name << endl;
cout << "Contribution: " << carray[i].contribution << endl << endl;
}
}
cout << "\n#####--#-Patrons-#--#####\n";
for (int d=0; d<contributors; d++){
if (carray[d].contribution < 10000){
cout << "Name: " << carray[d].Name << endl;
cout << "Contribution: " << carray[d].contribution << endl << endl;
}
}
inputfile.close();
return 0;
}
什麼是斷層?你有沒有試過在調試器中運行它?你在使用什麼IDE,OS? – OldProgrammer 2013-05-08 02:25:19
貢獻carray [貢獻者];你的編譯器讓你這麼做?它不應該是貢獻* carray =新貢獻[貢獻者]; ? – 2013-05-08 02:30:25
@JonathanHenson 不,這不是一個動態數組,只是一個結構數組,我原來使用了一個動態數組,但我認爲這可能是segfault背後的原因,所以我改爲靜態數組。無論哪種方式。 – 2013-05-08 02:36:20