gpt4 book ai didi

c++ - 如何以正确的方式将结构数组参数传递给函数?

转载 作者:行者123 更新时间:2023-12-01 23:05:26 30 4
gpt4 key购买 nike

源代码:

#include <iostream>

using namespace std;

struct Employee {

string name;
int age;
float salary;

};

void displayData(Employee);

int main() {

Employee employee[3];
int sizeOfEmployee = sizeof(employee) / sizeof(employee[0]);

for(int i = 0; i < sizeOfEmployee; i++) {
cout << "Enter name for employee " << i + 1 << ": ";
cin >> employee->name;
cout << "Enter age for employee " << i + 1 << ": ";
cin >> employee->age;
cout << "Enter salary for employee " << i + 1 << ": ";
cin >> employee->salary;
}

for(int i = 0; i < sizeOfEmployee; i++) {
displayData(employee[i]);
}

}

void displayData(Employee employee) {

cout << "DISPLAYING INFORMATION" << endl;
cout << "Name: " << employee.name << endl;
cout << "Age: " << employee.age << endl;
cout << "Salary: " << employee.salary << endl;

}

我的代码不显示我存储到数组中的所有数据,它只读取并显示我最后输入的数据。

代码输出:

CODE OUTPUT:

我可以用什么方式获取我存储到数组中的所有数据并显示它?

最佳答案

您正在将数据读取到指向数组第一个元素的指针中。要读入第 n 个元素,您的代码应该使用索引,例如 cin >> employee[i].name;

然而...

“裸”数组是许多错误、细微错误和通常不安全代码的来源。考虑改用 std::array - 这将消除对像 int sizeOfEmployee = sizeof(... 这样的代码的需要,并将很好地将该数组封装为函数的参数:

#include <array>

int main() {

std::array<Employee, 3> employee;

for(int i = 0; i < employee.size(); i++) {
cout << "Enter name for employee " << i + 1 << ": ";
cin >> employee[i].name;
// the rest of that for loop...
}
// and the second loop becomes:
for(const auto& e: employee) {
displayData(e);
}

关于c++ - 如何以正确的方式将结构数组参数传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71004156/

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