gpt4 book ai didi

c++ - 在类中构建数组和未处理的异常

转载 作者:行者123 更新时间:2023-11-28 07:18:22 25 4
gpt4 key购买 nike

我是编程新手,我正在尝试创建一个涉及数组的电话簿应用程序。我想从本质上获取大量联系人的信息,并让该人能够搜索他们。

每次我尝试编译代码时,它都有效,然后当我按 1 输入联系人并输入名字时,我得到这个“分配 7.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;

}

最佳答案

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] = "";
}
}

关于c++ - 在类中构建数组和未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19892976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com