30/09/2018, 16:15
[Wiki] Tạo 1 danh sách học sinh trong lớp học với struct
HEADER FILE
hocsinh.h
#pragma once
#include <iostream>
#include <string>
using namespace std;
#pragma pack(1)
struct hocsinh
{
char maSo[30];
char tenHS[30];
float diemToan, diemLy, diemHoa;
};
typedef struct hocsinh HOCSINH;
void nhapThongTinHocSinh(HOCSINH *);
void xuatThongTinHocSinhL(HOCSINH *);
float tinhDiemTrungBinh(HOCSINH *);
danhsach.h
#pragma once
#include "hocsinh.h"
#pragma pack(1)
struct lopHoc
{
HOCSINH *mang;
int soLuong;
};
typedef struct lopHoc LOPHOC;
void nhapDanhSachLopHoc(LOPHOC *);
void xuatDanhSachLopHoc(LOPHOC *);
SOURCE FILE
hocsinh.cpp
#include"hocsinh.h"
void nhapThongTinHocSinh(HOCSINH *x)
{
fflush(stdin);
cout << "
Nhap ma so hoc sinh:";
gets_s(x->maSo);
fflush(stdin);
cout << "
Nhap ten hoc sinh :";
gets_s(x->tenHS);
do
{
cout << "
Moi ban nhap diem Hoa cho hoc sinh :";
cin >> x->diemHoa;
if (x->diemHoa<0 || x->diemHoa>10)
{
cout << "
Diem Hoa ban nhap ko hop le vui long kiem tra lai!!!";
}
} while (x->diemHoa<0||x->diemHoa>10);
do
{
cout << "
Moi ban nhap diem Ly cho hoc sinh :";
cin >> x->diemLy;
if (x->diemLy<0 || x->diemLy>10)
{
cout << "
Diem Ly ban nhap ko hop le vui long kiem tra lai!!!";
}
} while (x->diemLy<0 || x->diemLy>10);
do
{
cout << "
Moi ban nhap diem Toan cho hoc sinh :";
cin >> x->diemToan;
if (x->diemToan<0 || x->diemToan>10)
{
cout << "
Diem Toan ban nhap ko hop le vui long kiem tra lai!!!";
}
} while (x->diemToan<0 || x->diemToan>10);
}
void xuatThongTinHocSinhL(HOCSINH *x)
{
cout << "
Thong tin hoc sinh :
";
cout << "
Ma so hoc sinh : " << x->maSo;
cout << "
Ten hoc sinh : " << x->tenHS;
cout << "
Diem toan : " << x->diemToan;
cout << "
Diem Ly : " << x->diemLy;
cout << "
Diem Hoa : " << x->diemHoa;
float diemTrungBinh = tinhDiemTrungBinh(x);
cout << "
Diem trung binh : " << diemTrungBinh;
}
float tinhDiemTrungBinh(HOCSINH *x)
{
return (x->diemHoa + x->diemLy + x->diemToan) / 3;
}
danhsach.cpp
#include "danhsach.h"
void nhapDanhSachLopHoc(LOPHOC *x)
{
for (int i = 0; i < x->soLuong; ++i)
{
cout << "
Nhap thong tin hoc sinh thu : " << i + 1;
nhapThongTinHocSinh(&(x->mang[i]));
}
}
void xuatDanhSachLopHoc(LOPHOC *x)
{
for (int i = 0; i < x->soLuong; ++i)
{
cout << "
Nhap thong tin hoc sinh thu : " << i + 1;
xuatThongTinHocSinhL(&(x->mang[i]));
}
}
main.cpp
#include "danhsach.h"
int main(int argc, char **argv)
{
LOPHOC *x = new LOPHOC;
do
{
cout << "
Nhap so luong cac hoc sinh";
cin >> x->soLuong;
if (x->soLuong < 0)
{
cout << "
So luong ban nhap ko hop le xin vui long kiem tra lai!!!";
}
} while (x->soLuong<0);
x->mang = new HOCSINH[x->soLuong];
nhapDanhSachLopHoc(x);
xuatDanhSachLopHoc(x);
system("pause");
return 0;
}
Bài liên quan