一、文件不存在时
//判断文件是否为空的标志 bool m_FileIsempty;
修改workermanager.cpp
//文件不存在 ifstream ifs; ifs.open(FILENAME, ios::in);//读文件 if (!ifs.is_open()) { cout << "文件不存在" << endl; //初始化属性 //初始化人数为零 this->m_EmpNum = 0; //初始化数组指针 this->m_EmpArray = NULL; //初始化文件是否为空 this->m_FileIsempty = true; ifs.close(); return; }
二、文件存在且数据为空
在workermanager.cpp中构造函数追加代码
//2.文件存在并且数据没有记录 char ch; ifs >> ch;//读一个字符 if (ifs.eof()) { //文件为空 cout << "文件为空" << endl; //初始化属性 //初始化人数为零 this->m_EmpNum = 0; //初始化数组指针 this->m_EmpArray = NULL; //初始化文件是否为空 this->m_FileIsempty = true; ifs.close(); return; }
三、文件存在数据存在
在.h中增加函数
//统计人数 int get_EmpNum();
。cpp中实现
int workManager::get_EmpNum() { ifstream ifs; ifs.open(FILENAME, ios::in);//打开文件 int id; string name; int dId; int num = 0; while (ifs >> id && ifs >> name && ifs >> dId) { //统计人数变量 num++; } return num; }
//三、文件存在且有数据 int num = this->get_EmpNum(); cout << "职工人数为:" << num << endl; this->m_EmpNum = num;
初始化
//初始化员工函数 void workManager::init_Emp() { ifstream ifs; ifs.open(FILENAME, ios::in); int id; string name; int dId; int index=0; while (ifs>>id&&ifs>>name&&ifs>>dId) { worker *worker = NULL; if (dId == 1)//普通职工 { worker = new Employee(id, name, dId); } else if (dId == 2)//经理 { worker = new Manager(id, name, dId); } else//老板 { worker = new Boos(id, name, dId); } this->m_EmpArray[index]=worker; index++; } ifs.close();//关闭文件 }
//三、文件存在且有数据 int num = this->get_EmpNum(){ cout<<"职工人数为:" << num << endl; this->m_EmpNum = num; void workManager::init_Emp() } //开辟空间 this->m_EmpArray = new worker*[this->m_EmpNum]; for (int i = 0; i<this->m_EmpNum; i++) { cout << "职工编号:" << this->m_EmpArray[i]->m_id << "姓名:" << this->m_EmpArray[i]->m_name << "部门编号:" << this->m_EmpArray[i]->m_DeptId << endl; }
原文:https://www.cnblogs.com/X404/p/14623914.html