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

โปรแกรม C++ จัดเก็บข้อมูลนักเรียนด้วย Structure


Structure รวมข้อมูลหลายชนิด ใช้คีย์เวิร์ด struct เหมาะสำหรับข้อมูลนักเรียน

ตัวอย่างโครงสร้างพนักงาน:

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

ตัวอย่างโค้ด (ข้อมูลนักเรียน)

#include <iostream>
using namespace std;

struct student {
    int rollNo;
    char name[50];
    float marks;
    char grade;
};

int main() {
    struct student s = { 12, "Harry", 90, 'A' };
    cout << "The student information is given as follows:" << endl;
    cout << endl;
    cout << "Roll Number: " << s.rollNo << endl;
    cout << "Name: " << s.name << endl;
    cout << "Marks: " << s.marks << endl;
    cout << "Grade: " << s.grade << endl;
    return 0;
}

ผลลัพธ์

The student information is given as follows:
Roll Number: 12
Name: Harry
Marks: 90
Grade: A

อธิบายโค้ด

กำหนด struct student มี rollNo, name, marks, grade:

struct student {
    int rollNo;
    char name[50];
    float marks;
    char grade;
};

สร้าง object s กำหนดค่า:

struct student s = { 12, "Harry", 90, 'A' };

แสดงข้อมูลด้วย dot operator:

cout<<"Roll Number: "<<s.rollNo<<endl;
cout<<"Name: "<<s.name<<endl;
cout<<"Marks: "<<s.marks<<endl;
cout<<"Grade: "<<s.grade<<endl;