#include<iostream>
#include<string>
#include<fstream>
#include<iomanip>
using namespace std;
class sinhvien {
private:
string masv[10];
string hoten[25];
float toan;
float ly;
float hoa;
float dtb;
public:
void settoan(float toan);
void setly(float ly);
void sethoa(float hoa);
void setmasv(string masv);
void sethoten(string hoten);
void setdtb();
void showInfo();
bool kiemtra();
sinhvien();
};
bool sinhvien::kiemtra() {
if (dtb >= 5 && toan != 0 && ly != 0 && hoa != 0) {
return 1;
}
return 0;
}
sinhvien::sinhvien() {
masv[0] = '\0';
hoten[0] = '\0';
toan = -1.0;
ly = -1.0;
hoa = -1.0;
}
void sinhvien::settoan(float toan) {
this->toan = toan;
}
void sinhvien::setly(float ly) {
this->ly = ly;
}
void sinhvien::sethoa(float hoa) {
this->hoa = hoa;
}
void sinhvien::setmasv(string masv) {
for (int i = 0;i < 10;i++) {
this->masv[i] = masv[i];
}
this->masv[masv.length()] = '\0';
}
void sinhvien::sethoten(string hoten) {
for (int i = 0;i < hoten.length();i++) {
this->hoten[i] = hoten[i];
}
this->hoten[hoten.length()] = '\0';
}
void sinhvien::setdtb() {
dtb = (toan * 3 + ly * 2 + hoa) / 6;
}
void sinhvien::showInfo() {
cout << "Ma sinh vien: ";
for (int i = 0;i < 10;i++) {
cout << *(masv + i);
}
cout << "\nHo ten: ";
for (int i = 0;i < 25;i++) {
cout << *(hoten + i);
}
cout << "\nDiem toan: " << toan << endl;
cout << "Diem ly: " << ly << endl;
cout << "Diem hoa: " << hoa << endl;
cout << "Diem trung binh: " << setprecision(3) << dtb << endl;
}
void writetofile(sinhvien a, ofstream& b) {
b.write((char*)& a, sizeof(sinhvien));
}
int main() {
ifstream ifs("Thisinh.txt");
sinhvien* a = new sinhvien[9];
string b;
float c;
if (!ifs) {
cout << "Loi\n";
}
else {
int i = 0;
while (!ifs.eof()) {
getline(ifs, b, '\t');
a[i].setmasv(b);
getline(ifs, b, '\t');
a[i].sethoten(b);
ifs >> c;
a[i].settoan(c);
ifs >> c;
a[i].setly(c);
ifs >> c;
a[i].sethoa(c);
a[i].setdtb();
getline(ifs, b, '\n');
i++;
}
}
ifs.close();
/*for (int i = 0;i < 9;i++) {
a[i].showInfo();
}*/
sinhvien p;
ofstream ofs("Thisinh.dat",ios::binary);
if (!ofs) {
cout << "Loi\n";
}
else {
for (int i = 0;i < 9;i++) {
if (a[i].kiemtra() == 1) {
//a[i].showInfo();
writetofile(a[i], ofs);
}
}
}
ofs.close();
ifstream ifs1("Thisinh.dat", ios::binary);
if (!ifs1) {
cout << "Loi\n";
}
else {
while (!ifs1.eof() ) {
ifs1.read((char*)&p, sizeof(sinhvien));
if (ifs1.good()) {
p.showInfo();
}
}
}
ifs1.close();
delete[] a;
system("pause");
return 0;
}
Đây là bài code của em.
Khi em đọc file nhị phân thì nó vẫn hiển thị đầy đủ nội dung những cuối cùng vẫn báo lỗi .
Mọi người có thể giải thích cho em không ạ?
Em cám ơn.