#include <iostream>
#include <fstream>
#include <cstring>
#include "student.h"
#define max 100
using namespace std;
void ReadFile(Student** sv, int &soSV){
ifstream file;
file.open("sinhvien.txt");
if(file.fail()){
cout<<"Cannot open file!";
return;
}
soSV = 0;
while(!file.eof()){
string str;
getline(file,str);
if(str.length()>0){
string info[5];
int n=0;
int end = -1;
while(str.length()>0){
end = str.find("|",0);
if(end>-1){
info[n] = str.substr(0,end);
str.erase(0,end+1);
} else {
info[n] = str;
str.erase(0,str.length());
}
n++;
}
sv[soSV] = new Student(info[0], info[1], info[2], info[3], info[4]);
soSV++;
}
}
file.close();
}
int main() {
int SoSV;
Student** sv;
sv = new Student*[max];
for(int i=0;i<max;i++) sv[i] = new Student();
ReadFile(sv, SoSV);
cout<<"Hien thi danh sach sinh vien:"<<endl;
for(int i=0; i<SoSV; i++){
sv[i]->Display();
}:joy:
return 0;
}
student.h
#ifndef _STUDENT_H_
#define _STUDENT_H_
#include <cstring>
using namespace std;
class Student{
private:
string MaSV;
string HoTen;
string NgaySinh;
string GioiTinh;
string LopQL;
public:
Student();
Student(Student&);
Student(string, string, string, string, string);
void Read();
void Display();
};
#endif
student.cpp
#include <iostream>
#include <iomanip>
#include "student.h"
using namespace std;
Student::Student(){
MaSV = "";
HoTen = "";
NgaySinh = "";
GioiTinh = "";
LopQL = "";
}
Student::Student(Student& sv){
MaSV = sv.MaSV;
HoTen = sv.HoTen;
NgaySinh = sv.NgaySinh;
GioiTinh = sv.GioiTinh;
LopQL = sv.LopQL;
}
Student::Student(string masv, string hoten, string ngaysinh, string gioitinh, string lopql){
this->MaSV = masv;
this->HoTen = hoten;
this->NgaySinh = ngaysinh;
this->GioiTinh = gioitinh;
this->LopQL = lopql;
}
void Student::Read(){
cout<<"Ma SV: ";
fflush(stdin);
cin>>MaSV;
cout<<"Ho ten: ";
fflush(stdin);
cin>>HoTen;
cout<<"Ngay sinh: ";
fflush(stdin);
cin>>NgaySinh;
cout<<"Gioi tinh: ";
fflush(stdin);
cin>>GioiTinh;
cout<<"Lop QL: ";
fflush(stdin);
cin>>LopQL;
}
void Student::Display(){
cout<<left<<setw(10)<<MaSV<<" | ";
cout<<left<<setw(30)<<HoTen<<" | ";
cout<<setw(10)<<NgaySinh<<" | ";
cout<<left<<setw(3)<<GioiTinh<<" | ";
cout<<left<<setw(6)<<LopQL<<endl;
}
E có thắc mắc là tại sao phải khởi tạo sv[i] = new Student(); bên ngoài rồi bên trong phải sv[soSV] = new Student(info[0], info[1], info[2], info[3], info[4]); mới chạy được. Nếu không nó sẽ không nhận được ô nhớ và crash.
Trời ơi, ai xem rồi có í kiến gì thì giúp e với. 






83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?