C++ 程序使用结构保存并显示信息
结构是对不同数据类型的项的集合。在创建具有不同数据类型记录的复杂数据结构时,它非常有用。用 struct 关键字定义结构。
下面是一个结构的示例 -
struct employee { int empID; char name[50]; float salary; };
一个用于使用结构存储和显示信息的程序如下。
示例
#include <iostream> using namespace std; struct employee { int empID; char name[50]; int salary; char department[50]; }; int main() { struct employee emp[3] = { { 1 , "Harry" , 20000 , "Finance" } , { 2 , "Sally" , 50000 , "HR" } , { 3 , "John" , 15000 , "Technical" } }; cout<<"The employee information is given as follows:"<<endl; cout<<endl; for(int i=0; i<3;i++) { cout<<"Employee ID: "<<emp[i].empID<<endl; cout<<"Name: "<<emp[i].name<<endl; cout<<"Salary: "<<emp[i].salary<<endl; cout<<"Department: "<<emp[i].department<<endl; cout<<endl; } return 0; }
输出
The employee information is given as follows: Employee ID: 1 Name: Harry Salary: 20000 Department: Finance Employee ID: 2 Name: Sally Salary: 50000 Department: HR Employee ID: 3 Name: John Salary: 15000 Department: Technical
在上述程序中,在 main() 函数之前定义结构。该结构包含一个员工的员工 ID、姓名、薪资和部门。以下代码片段对此进行了演示。
struct employee { int empID; char name[50]; int salary; char department[50]; };
在 main() 函数中,定义了一个类型为 struct employee 的对象数组。其中包含员工 ID、姓名、薪资和部门值。如下所示。
struct employee emp[3] = { { 1 , "Harry" , 20000 , "Finance" } , { 2 , "Sally" , 50000 , "HR" } , { 3 , "John" , 15000 , "Technical" } };
使用 for 循环显示结构值。如下所示。
cout<<"The employee information is given as follows:"<<endl; cout<<endl; for(int i=0; i<3;i++) { cout<<"Employee ID: "<<emp[i].empID<<endl; cout<<"Name: "<<emp[i].name<<endl; cout<<"Salary: "<<emp[i].salary<<endl; cout<<"Department: "<<emp[i].department<<endl; cout<<endl; }
广告