访问结构时出现分段错误

时间:2014-04-16 16:35:51

标签: c++ arrays segmentation-fault structure core

程序一直工作,直到它检查用户输入的名称。当您在从完整客户信息的文件导入的结构数组中输入您要搜索的名称时,它会返回分段故障核心转储。这让我很困惑。

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

1 个答案:

答案 0 :(得分:0)

你的循环继续将所有内容读入数组的初始元素:

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

因为i的值永远不会递增。您可以将其转换为for循环,如下所示:

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

请注意,我已将i更改为count

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

这将帮助您解决另一个问题 - 确定数组何时在getAccount函数中结束。目前,您假设记录始终存在,因此外部循环继续进行。现在您已经count,您可以像这样更改循环:

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