访问结构时出现分段错误

问题描述 投票:0回答:1

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

#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;
}
c++ arrays segmentation-fault structure
1个回答
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.