2013-05-08 2 views
-1

내 프로그램에서 한 줄씩 텍스트 파일을 읽으면 기부자 그룹에 대한 정보를 얻을 수 있습니다. 정보 (이름, 기부 금액)를 저장하기 위해 구조체 배열을 사용합니다. 텍스트 파일의 첫 번째 행은 참여자 수입니다. 그 때부터 줄은 기부금의 이름과 가치를 나타냅니다. 예 : 자신의 기부금이 10,000 이상인 경우내 프로그램에서 세그먼테이션 오류가 발생했습니다 (C++)

3 
Kyle Butler 
10340 
James Wright 
5006 
John Smith 
10000 

그런 다음, 자신의 이름과 기부 값이 제목 아래 화면에 출력은 "그랜드 후원자는"그렇지 않으면 "후원자"

제목 아래에 나타납니다 문제는 프로그램을 실행할 때 화면에 아무 것도 출력하지 않는 증거로 세그멘테이션 오류가 발생한다는 것입니다. 누군가 여기서 무슨 일이 일어나는지 말해 주실 수 있습니까? 나는 언어에 상당히 익숙하다. 당신은 모든에 pointerindex를 증가하고

#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; 
} 
+2

어떤 라인이 오류가 있습니까? 디버거에서 실행 해 보셨습니까? 어떤 IDE, OS를 사용하고 있습니까? – OldProgrammer

+1

기여하다 [기여자]; 당신 컴파일러가 이러는거야? 기여하지 않아야합니다 * carray = new contribution [contributers]; ? –

+0

@JonathanHenson 아니요, 이것은 동적 배열이 아니며 단지 구조 배열입니다. 원래 동적 배열을 사용했지만 정적 요소로 변경된 이유로 세그 폴트의 원인이 될 수 있다고 생각했습니다. 어느 쪽이든 작동합니다. –

답변

0

당신이 공헌 금액에서 읽은 직후보다는 루프를 통해 전달합니다. 따라서 5006에서 읽을 때가되면 pointerindex == 3이 생기므로 carray[pointerindex]에 segfault가 발생합니다.

++pointerindexelse 문으로 이동하십시오.

+0

정말 고마워요! 나는 그것이 단순한 무언가 일 것이라는 것을 알고 갑자기 많은 감각을 갖습니다! –

관련 문제