2014-04-16 3 views
0

사용자가 입력 한 이름을 확인할 때까지 프로그램이 계속 작동합니다. 고객 정보로 가득 찬 파일에서 가져온 구조체 배열에서 검색하려는 이름을 입력하면 코어가 덤프 된 세그먼테이션 오류가 다시 발생합니다. 이 퍼즐.구조체에 액세스 할 때 세그먼트 오류

#include <iostream> 
#include <string> 
#include <fstream> 
#include <cstring> 
using namespace std; 

struct AccountsDataBase{ 

     char name[50]; 
     string email; 
     long int phone; 
     string address; 
}; 


#define MAX 80 

AccountsDataBase * account = new AccountsDataBase[MAX]; 


void readIn(ifstream& file){ 
     int i=0; 
     while(!file.eof()){ 
       file >> account[i].name >> account[i].email >> account[i].phone >> account[i].address; 
     } 
} 

void getAccount(){ 

     char userPick[50]; 
     char streamName[50]; 

     cout << " What account will we be using? " << endl; 

     cin.getline(streamName, 50); 

     for(int i=0; strcmp(account[i].name, streamName)!=0; i++){ 
       if(strcmp(account[i].name, streamName)==0){ 
         cout << "\n\n FOUND IT!! \n\n"; 
         cout << account[i].name << "\n" << account[i].email << "\n" << account[i].phone << "\n" << account[i].address << endl; 
       } 
     } 
} 

int main(){ 
     ifstream file; 
     file.open("2.dat"); //opens data account records text 
     readIn(file); 
     getAccount(); 
     delete account; 
     return 0; 
} 
+0

음 : 이제 count 가지고,이 같은 루프를 바꿀 수 있을까? – OldProgrammer

+0

@ 콜린 오류가 특정 라인을 나타내지 않는 한 라인 번호는 필요 없습니다. – yizzlez

+0

@ 콜린 http://meta.stackexchange.com/questions/40164/should-we-close-fix-my-program-questions – sashoalm

답변

0

루프는 배열의 초기 요소로 모든 것을 읽는 계속 : i의 값이 증가되지 않습니다

while(!file.eof()){ 
    file >> account[i].name >> account[i].email >> account[i].phone >> account[i].address; 
} 

때문이다. 이처럼 for 루프이 변환 할 수 있습니다 : 나는 counti을 변경

for (count = 0 ; count < MAX && !file.eof() ; count++) { 
    file >> account[count].name >> account[count].email >> account[count].phone >> account[count].address; 
} 

참고 :이 다른 문제를 해결하는 데 도움이 될 것입니다

AccountsDataBase * account = new AccountsDataBase[MAX]; 
int count = 0; 

- 배열이 getAccount에 종료 될 때 결정을 기능. 현재 레코드가 항상 있다고 가정하므로 외부 루프가 계속 진행됩니다. 먼저 디버거에서 코드를 밟은,

for(int i=0; i < count && strcmp(account[i].name, streamName)!=0; i++){ 
    if(strcmp(account[i].name, streamName)==0){ 
     cout << "\n\n FOUND IT!! \n\n"; 
     cout << account[i].name << "\n" << account[i].email << "\n" << account[i].phone << "\n" << account[i].address << endl; 
     break; 
    } 
} 
if (i == count) { 
    cout << "Not found." << endl; 
} 
+0

첫 번째 답변은 내 부분에 어리석은 실수였습니다. 두 번째 부분은 내 지식을 넘어서서 그 문제를 해결하는 방법을 알지 못했지만 루프를 업데이트하고 전체 메모리 맵을 인쇄하고 있기 때문에 완전히 새로운 유형의 세그먼테이션 결함을 제공합니다. –

+0

@ColinRickels 편집, 새로운 세그 폴트를 쉽게 발견 할 수 있어야합니다. – dasblinkenlight

관련 문제