Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ จัดเก็บและแสดงข้อมูลพนักงานด้วย Structure


Structure (โครงสร้าง) คือการรวมข้อมูลหลายชนิด (data types) เข้าด้วยกัน เหมาะสำหรับสร้างข้อมูลซับซ้อน ใช้คีย์เวิร์ด 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

อธิบายโค้ด

กำหนด struct employee มี empID, name, salary, department:

struct employee {
    int empID;
    char name[50];
    int salary;
    char department[50];
};

ใน main() สร้างอาร์เรย์ emp[3] เก็บข้อมูลพนักงาน 3 คน:

struct employee emp[3] = {
    { 1, "Harry", 20000, "Finance" },
    { 2, "Sally", 50000, "HR" },
    { 3, "John", 15000, "Technical" }
};

แสดงข้อมูลด้วย for loop ใช้ dot operator (.) เข้าถึงสมาชิก:

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;
}