我应该创建一个包含名为Person的类的AddressBook。我的程序几乎可以正常工作,除非我添加一个人,它在命令菜单的下一次迭代中不会记住它并且显示全部显示"您的地址簿中有0个人。&#34 ;我的代码出了什么问题?
#include <iostream>
#include <string>
using namespace std;
class AddressBook {
public:
class Person
{
public:
char firstName[15];
char lastName[15];
char personID[15];
};
Person entries[100];
unsigned int total;
AddressBook()
{
total = 0;
}
void AddPerson()
{
cout << "This is entry number " << (total + 1) << " in your address book. " << endl;
cout << "What shall we put for the first and last name? Limit both to under 15 characters. Example: Bob Smith" << endl;
cin >> entries[total].firstName >> entries[total].lastName;
cout << "What is " << entries[total].firstName << " " << entries[total].lastName << "'s ID code?" << endl;
cin >> entries[total].personID;
++total;
cout << "..." << endl << "Successfully Added." << endl;
};
void DisplayPerson(int i)
{
cout << "Entry " << i + 1 << ": " << endl;
cout << "FIRST NAME: " << entries[i].firstName << endl;
cout << "LAST NAME: " << entries[i].lastName << endl;
cout << "ID: " << entries[i].personID << endl;
};
void DisplayEveryone()
{
cout << "You have " << total << " People in your address book." << endl;
for (int i = 0; i < total; ++i)
DisplayPerson(i);
};
void SearchPerson()
{
char lastname[32];
cout << "Please enter the last name of the person you wish to find." << endl;
cin >> lastname;
for (int i = 0; i < total; ++i)
{
if (strcmp(lastname, entries[i].lastName) == 0)
{
cout << "Person Found. " << endl;
DisplayPerson(i);
cout << endl;
}
}
};
};
int main() {
char command;
bool Exit = false;
while (Exit == false)
{
AddressBook Address_Book;
cout << "---------------COMMANDS---------------" << endl;
cout << "A: Add Person To Address Book" << endl;
cout << "S: Search for Person in Address Book" << endl;
cout << "D: Display Everyone In Address Book" << endl << endl;
cout << "Type the letter of your command: ";
cin >> command;
cout << endl;
switch (command) {
case 'A':
case 'a':
Address_Book.AddPerson();
break;
case 'S':
case 's':
Address_Book.SearchPerson();
break;
case 'D':
case 'd':
Address_Book.DisplayEveryone();
break;
default:
cout << "That is not a valid command. Closing Address Book." << endl;
cout << endl;
}
}
}
答案 0 :(得分:2)
原因是您在while循环的每次迭代中创建一个新的地址簿,并在迭代结束时将其丢弃:
这个
AddressBook Address_Book;
创建一个新的地址簿,然后扔掉#34;当你到达其范围的末尾时(即循环结束)。
实际上,无论何时想要新的地址,你都会购买新的地址簿吗?不。你首先购买这本书,然后(可能在一个循环中)你添加条目。将上面一行移到循环之外。
答案 1 :(得分:1)
您的问题出在您的地址簿声明中。
将其更改为以下内容:
AddressBook Address_Book;
while (Exit == false) {
//Ask for input and respond.
}
在您的版本中Address_Book
在while
循环开始时声明。这意味着每次循环的迭代完成并且执行返回到块的开头时,就会创建一个不知道先前对象数据的新本地Address_Book
对象。