0

我对编程很陌生,我试图创建一个涉及数组的电话簿应用程序。我想从本质上获取大量联系人的信息,并让该人能够搜索它们。

每次我尝试编译代码时,它都可以工作,然后当我按 1 输入联系人并输入名字时,我得到这个“在 assignment7.23.exe 中 0x000f2ceb 处未处理的异常:0xC0000005:访问冲突读取位置0x99d0627c。”

我不确定这意味着什么或我的代码有什么问题。

先感谢您。

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

class AddressBook {

public:

string myContactsFirstName[100];
string myContactsLastName[100];
string myContactsEmailAddress[100];
string myContactsPhone[100];
int index;

AddressBook() {
    int index = 0;
    for (int i = 0; i < 100; i++) {
        myContactsFirstName[i] = "";
        myContactsLastName[i] = "";
        myContactsEmailAddress[i] = "";
        myContactsPhone[i] = "";
    }
}

void addContact() {
    cout << "Enter the first name of the contact: " << endl;
    string firstname;
    cin >> firstname;
    myContactsFirstName[index] = firstname;

    cout << "Last Name:" << endl;
    string lastname;
    cin >> lastname;
    myContactsLastName[index] = lastname;

    cout << "Phone Number: " << endl;
    string phone;
    cin >> phone;
    myContactsPhone[index] = phone;

    cout << "Email Address: " << endl;
    string address;
    cin >> address;
    myContactsEmailAddress[index] = address;

    system("pause");
    index++;
}

    void deleteLastContact(){
        myContactsFirstName[index] = "";
        myContactsLastName[index] = "";
        myContactsPhone[index] = "";
        myContactsEmailAddress[index] = "";
        index--;

        cout << "Contact deleted." << endl;


    }
};

int main() {
AddressBook myPeople;
string target;

while(1){
    cout << "Enter 1 to add a contact." << endl;
    cout << "Enter 2 to search contacts." << endl;
    cout << "Enter 3 to delete a contact." << endl;
    cout << "Enter anything else to leave the program" << endl;

    int choice;
    cin >> choice;

    switch (choice) {
        case 1: myPeople.addContact();
            break;
        case 2: {
        cout << "Enter the info to search for your contact:" << endl;
        cin >> target;

        for (int i = 0; i < myPeople.index; i++) {
            if (myPeople.myContactsFirstName[i].compare(target) == 0 )
                    cout << "We have a match" << endl;
        }
            break;
                }

        case 3: {
            myPeople.deleteLastContact();
            break;
                }
        default: exit(0);

}
}

    system("pause");
    return 0;

}
4

1 回答 1

1

Index未初始化:

AddressBook() {
   int index = 0; //created a new index variable, fix this by deleting "int"
   ^^^
   for (int i = 0; i < 100; i++) {
      myContactsFirstName[i] = "";
      myContactsLastName[i] = "";
      myContactsEmailAddress[i] = "";
      myContactsPhone[i] = "";
      }
}
于 2013-11-10T18:02:24.343 回答