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;
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP