因此,我尝试使用结构数组,您在其中输入自己的值到每个变量中。它的总体思路是,我希望用户输入5个不同的员工姓名,ID和年薪。该程序旨在输出结构数组。
但是,我的问题是,当我尝试输出数组时,输出似乎只显示数组的最后一个元素5倍。
感谢所有帮助!
p.s。不用担心平均功能,我想自己找出一个。
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
struct emp
{
char empName[25];
int id;
float salary;
};
struct emp employee[5];
struct emp *getData();
void printData(struct emp employee[]);
int main()
{
cout << "Enter employee name, ID and Annual Salary: " << endl;
struct emp *p;
p = getData();
printData(employee);
}
struct emp *getData()
{
for (int i = 0; i < 5; i++)
{
cout << "Employee " << i + 1 << " name: ";
cin >> employee->empName;
cout << "Employee " << i+1 << " ID: ";
cin >> employee->id;
cout << "Employee " << i+1 << " Annual Salary: ";
cin >> employee->salary;
cin.ignore();
cout << endl;
}
return employee;
}
void printData(struct emp employee[])
{
for (int i = 0; i < 5; i++)
{
cout << "Employee " << i + 1 << ": " << employee->empName << " - " << employee->id << ", Annual Salary: " <<
employee->salary << endl;
}
}
//double getAverage(struct emp[], int)
//{
//
//}
输出
Enter employee name, ID and Annual Salary:
Employee 1 name: Ian
Employee 1 ID: 2345
Employee 1 Annual Salary: 12345
Employee 2 name: John
Employee 2 ID: 2345
Employee 2 Annual Salary: 23456
Employee 3 name: Carla
Employee 3 ID: 23452
Employee 3 Annual Salary: 2345
Employee 4 name: Chloe
Employee 4 ID: 12345
Employee 4 Annual Salary: 2345
Employee 5 name: Josh
Employee 5 ID: 234
Employee 5 Annual Salary: 12345
Employee 1: Josh - 234, Annual Salary: 12345
Employee 2: Josh - 234, Annual Salary: 12345
Employee 3: Josh - 234, Annual Salary: 12345
Employee 4: Josh - 234, Annual Salary: 12345
Employee 5: Josh - 234, Annual Salary: 12345
Press any key to continue . . .
答案 0 :(得分:0)
您没有使用任何数组块,因此所有输入都进入第一个,所有输出都来自第一个。
for (int i = 0; i < 5; i++)
{
cout << "Employee " << i + 1 << " name: ";
cin >> employee[i].empName;
cout << "Employee " << i+1 << " ID: ";
cin >> employee[i].id;
cout << "Employee " << i+1 << " Annual Salary: ";
cin >> employee[i].salary;
cin.ignore();
cout << endl;
}
return employee;
}
void printData(struct emp employee[])
{
for (int i = 0; i < 5; i++)
{
cout << "Employee " << i + 1 << ": " << employee[i].empName << " - " << employee[i].id << ", Annual Salary: " <<
employee[i].salary << endl;
}
}
这应该解决您的代码