我正在进行一项具有以下目标的任务:
- Store user provided customer info into an array of structs.
- Write functions to add, display all or retrieve a customer(s).
我在编写 findCust(检索例程)时遇到问题。我想提示用户输入任何客户的名字和姓氏,然后在客户数组中找到相关客户并打印出他们的信息。我有点卡住了,不确定如何继续。
这是我目前所拥有的:
void findCust(Customer customers[], int loc)
{
string name;
const int t = 100;
cout << "\nEnter the name of the customer you would like to look up: ";
getline(cin, name);
cout << endl;
for (int i = 0; i <= loc; i++) {
}
}
Customer 结构是这样的:
struct Customer {
string firstname;
string lastname;
Address home;
Address business;
};
这是我的主要功能:
int main() {
title("Customer Contact Menu");
int choice = 0;
int loc = 0;
const int SIZE = 100;
Customer contacts[SIZE];
while (choice < 5) {
choice = displayMenu();
switch (choice) {
case 1:
contacts[loc] = getCustomer();
loc++;
break;
case 2:
for (int x = 0; x < loc; x++) {
showCustomer(contacts[x]);
}
break;
case 3:
findCust(contacts,loc);
break;
case 4:
endProg();
}
}
}
我想知道如何准确读取存储在客户数组中的信息,并将其与用户输入进行比较。我尝试使用 customer.compare 命令,我也尝试过一些东西,我尝试过线性搜索等。但问题是用户输入无法与结构进行比较。这就是我坚持的部分。
最佳答案
如果我正确理解了您的问题,您希望阅读并找到客户,然后打印他们的信息。为了做到这一点,我会像这样构造函数:
void findCust(Customer customers[], int array_size)
{
string first_name, last_name;
cout << "\nEnter the name of the customer you would like to look up: ";
cin >> first_name >> last_name;
for (int i = 0; i < array_size; i++) {
}
}
在 for 循环中,您可以运行线性搜索并遍历所有客户并进行比较。即遍历数组并为每个 customers[i].firstname
和 customers[i].lastname
检查它们是否匹配 first_name
和 last_name
变量。
如果他们这样做,则调用 print(customers[i])
,这是将打印出给定客户的函数。您可以使函数的定义类似于 void print(Customer customer)
,这可以包含流中的所有打印。
希望这能帮助您入门。
关于c++ - 从结构化数组中读取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54927797/