c++arrayssegmentation-faultstructure

Segmentation fault when accessing a structure


The program works all the way up until it checks for the name the user enters. When you enter the name you wish to search for in the array of structures that have been imported from a file full of customer info) it comes back segmentation fault core dumped. This puzzles me.

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

Solution

  • Your loop keeps reading everything into the initial element of the array:

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

    because the value of i is never incremented. You can convert this to a for loop, like this:

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

    Note that I changed i to count:

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

    This will help you solve another problem - determining when the array ends in the getAccount function. Currently, you assume that the record is always there, so the outer loop keeps going on. Now that you have count, you could change the loop like this:

    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;
    }