C++ project - employee management system

Table of contents

 

foreword

1. Management system requirements

2. The functions that need to be implemented in the management system are as follows:

Second, create a management class

2.1 Create a file

2.2 Implementation of the header file

2.3 Realization of source files

 3. Create a menu

4. Exit the system 

5. Create an employee class

5.1 Create worker abstract class

 5.2 Create a common employee class

6. Add employees

6.1 Functional Analysis

7. File interaction 

7.1 Writing files

7.2 Reading files 

7.1.1 File not created

 7.1.2 The file exists but the data is empty

7.1.3 The file exists and has data

 7.3 Initializing arrays

8. Show employees

9. Delete employees 

10. Modify employees

11. Find employees

12. Sorting 

Thirteen, clear the file

Summarize


foreword

1. Management system requirements

The employee management system can be used to manage the information of all employees in the company

This tutorial mainly uses C++ to implement a polymorphic-based employee management system

Employees in the company are divided into three categories: ordinary employees, managers, and bosses. When displaying information, it is necessary to display the employee number, employee name, employee position, and responsibility.                                                                                                                         

Responsibilities of ordinary employees: Complete the tasks assigned by the manager.
Responsibilities of the manager: Complete the tasks assigned by the boss, and issue tasks to employees.
Responsibilities of the boss : Manage all affairs of the company

2. The functions that need to be implemented in the management system are as follows:

1. Exit the management program: exit the current management system
2. Add employee information: realize the function of adding employees in batches, and enter the information into the file. The employee information is: employee number, name, department number                                                                                                                                                3. Display employee information: display all information in the company Employee information
4. Delete resigned employees: delete designated employees according to the number. Modify employee information: modify employee personal information according to the number. 5.
Find employee information: search for relevant personnel information according to the employee number or employee name.                                      Sorting: Sort according to the employee number, and the sorting rules are specified by the user.
7. Clear all files: Clear all employee information recorded in the file (you need to confirm again before clearing to prevent accidental deletion)


1. Create a project

Create a new project in VS2022. For the creation method, please refer to an article I wrote "Simple Setup of VS2022".

Second, create a management class

The management class is responsible for the following:

1. Communication menu interface with users

2. The operation of adding, deleting, modifying and checking employees

3. Interaction with reading and writing of files

2.1 Create a file

Create workerManager.h and workerManager.cpp files under the header file and source file folders respectively

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
import  ssl
ssl._create_default_https_context = ssl._create_unverified_context

2.2 Implementation of the header file

#pragma once
#include<iostream>
using namespace std;
class WorkerManager
{
public:
    //构造函数
    WorkerManager();
    //析构函数
    ~WorkerManager();
};

2.3 Realization of source files

#include"workerManager.h"
WorkerManager::WorkerManager()
{
}
WorkerManager::~WorkerManager()
{
}

 3. Create a menu

Function: Interface to communicate with users.

Create the menu member function of WorkerManager under workerManager.cpp:

void WorkerManager::menu()
{
	cout << "*******************************************" << endl;
	cout << "**********欢迎使用职工管理系统!************" << endl;
	cout << "***************1.增加职工信息**************" << endl;
	cout << "***************2.显示职工信息**************" << endl;
	cout << "***************3.删除离职职工**************" << endl;
	cout << "***************4.修改职工信息**************" << endl;
	cout << "***************5.查找职工信息**************" << endl;
	cout << "***************6.按照编号排序**************" << endl;
	cout << "***************7.清空所有文档**************" << endl;
	cout << "*******************************************" << endl;
	cout << endl;
}

4. Exit the system 

Branch selection is provided in the main function, providing each functional interface.

Case 0 in the switch: add return 0 below to exit the system.

5. Create an employee class

5.1 Create worker abstract class

Employees are classified into: ordinary employees, managers, bosses

Abstract the three types of workers into one class (worker) , and use polymorphism to manage different types of workers

The attributes of employees are: employee number, employee name, employee department number

The employee's behavior is: describe the job responsibilities information, get the job title

Create a worker.h file under the header file folder and add the following code:

#pragma once
#include<iostream>
using namespace std;
class worker//职工抽象基类
{
public:
	//显示个人信息
	virtual void perinf() = 0;
	//岗位信息
	virtual string jobname() = 0;
	int m_id;
	string m_name;
	int m_depid;
};

 5.2 Create a common employee class

The ordinary employee class inherits the employee abstract class, and rewrites the pure virtual function in the parent class.
Create job.h and job.cpp files under the header file and source file folders respectively

Write the function declaration of the employee subclass in the job.h header file

using namespace std;
#include<string>
#include"work.h"
//在这里仅作为员工的声明
class employee :public worker
{
public:
	//构造函数
	employee(int id,string name,int depid);
	//显示个人信息
	void perinf();
	//岗位信息
	string jobname();
};

Write the specific implementation of the function in the job.cpp source file

#include"job.h"
//普通员工类
//构造函数
employee::employee(int id, string name, int depid)
{
	this->m_id = id;//这里不加this也可以,因为编译器在类的成员函数中自动用this指针
	this->m_name = name;
	this->m_depid = depid;
}
//显示个人信息
void employee::perinf()
{
	cout << "职工编号:" << this->m_id
		<< "\t职工姓名:" << this->m_name
		<< "\t岗位:" << this->jobname()
		<<"\t岗位职责:完成经理交给的任务。"<<endl;
}
//获取岗位名称
string employee::jobname()
{
	return string("员工");
}

In the same way, you can write manager and boss classes.

6. Add employees

Function description: Add employees in batches and save them in a file

6.1 Functional Analysis

Analysis: When users create in batches, they may create different types of employees. If you want to put all different types of employees into an array, you can maintain the pointers of all employees into an array. If you want to maintain this variable-length array in the program, you can create the array in the heap area and use the pointer of Worker** to maintain it.

 work** : secondary pointer, pointer to pointer.

        First, in the class WorkerManager class in workerManager.h, add a member attribute int m_EmpNum to record the number of employees, a worker array pointer worker** m_Emparray and a member function declaration void add_emp();, this add_emp() function Used to add worker operations.

        Then write the specific implementation in workManager.cpp. First, initialize the attributes outside the class. You need to add a scope. Use the this pointer to point to the member attributes and assign the initial value. code show as below:

WorkerManager::WorkerManager()
{
	//初始化属性
	this->m_EmpNum = 0;
	this->m_Emparray = NULL;
}

        Then start writing the implementation of the function add_emp() to add employees. Similarly, this function should also define an integer variable addnum under the scope of "WorkerManager::", which is used to save the number of users. When addnum > 0 , add the number of employees and calculate the size of the added new space, define a new integer variable newsize to store the new number of employees, set int newsize = this->m_EmpNum + addnum. Open up a new pointer to the array of pointers worker**newspace = new worker * [newsize] . Then copy the data in the original space to the new space (equivalent to saving the subclass objects in each small box in the parent class object in a large box in the above picture), and then write the command for the user to add data , save the created employee pointer to the array newspace, and finally need to release the original space, change the pointer to the new space, update the new number of employees, and prompt that the addition is successful. Below is the code:

//添加职工
void WorkerManager::add_emp()
{
	cout << "请输入添加职工的数量: " ;
	int addnum = 0;//用于保存用户的数量
	cin >> addnum;
	if (addnum > 0)
	{
		//添加职工的数量
		int newsize = this->m_EmpNum + addnum;//计算添加新空间的大小
		//开辟新空间
		worker**newspace = new worker * [newsize];
		//将原来空间下的数据,拷贝到新空间下
		if (this->m_Emparray != NULL)
		{
			for (int i = 0; i < this->m_EmpNum; i++)
			{
				newspace[i] = this->m_Emparray[i];
			}
		}
		int m_id;//职工编号
		string m_name;//职工姓名
		int m_depid;//职工所在部门名称编号
		//批量添加新数据
		for (int i = 0; i < addnum; i++)
		{
			cout << "请输入第" << i + 1 << "个新职工的编号:";
			while (1)
			{
				int a = 0;
				cin >> m_id;
				for (int i = 0;i < this->m_EmpNum;i++)
				{
					if (m_id == this->m_Emparray[i]->m_id)
					{
						cout << "编号已经存在,请重新输入编号。" << endl;
						a = 1;
					}
				}
				if (a == 0)
				{
					break;
				}
			}
			cout << "请输入第" << i + 1 << "个新职工的姓名:";
			cin >> m_name;
			cout << "请输入第" << i + 1 << "个新职工的岗位(1.员工 2.经理 3.老板):";
			cout << endl;
			worker* wk = NULL;
			again:cin >> m_depid;
			switch (m_depid)
			{
			case 1:
				wk = new employee(m_id, m_name, 1);
				break;
			case 2:
				wk = new manager(m_id, m_name, 2);
				break;
			case 3:
				wk = new boss(m_id, m_name, 3);
				break;
			default:
				cout << "非法输入请重新输入" << endl;
				goto again;
				break;
			}	
			//将创建的职工指针,保存到数组newspace中
			newspace[this->m_EmpNum + i] = wk;
		}
		//释放原有空间
		delete[] this->m_Emparray;
		//更改新空间的指向
		this->m_Emparray = newspace;
		//更新新的职工人数
		this->m_EmpNum = newsize;
		//更新职工不为空的标志
		this->m_FilelsEmpty = false;
		//提示添加成功
		cout << "添加"<<addnum<<"名新员工成功" << endl;
		//保存数据到文件中
		this->save();
	}
	else
	{
		cout << "输入有误,请重新输入" << endl;
	}
	system("pause");
	system("cls");
}

 Finally free the memory in the ~WorkerManager() destructor and set the pointer to a null pointer.

WorkerManager::~WorkerManager()
{
	if (this->m_Emparray != NULL)
	{
		delete[]this->m_Emparray;
		this->m_Emparray = NULL;
	}
}

7. File interaction 

Function description : read and write files

In the last add function, we just added all the data to memory, which cannot be saved once the program ends. Therefore, the file management class needs a function to interact with files, to read and write files 

7.1 Writing files

First, we add the file path, add macro constants in workerManager.h, and include the header file fstream, add the member function void save() in the class in workerManager.h, and write the implementation of save() in workerManager.cpp.

//保存文件
void WorkerManager::save()
{
	ofstream ofs;
	ofs.open(FILENAME, ios::out);//用输出的方式打开文件写文件
	//将每个人数据写入到文件中
	for (int i = 0; i < this->m_EmpNum; i++)
	{
		ofs << this->m_Emparray[i]->m_id << "\t"
			<< this->m_Emparray[i]->m_name << "\t"
			<< this->m_Emparray[i]->m_depid << "\t";
	}
	//关闭文件
	ofs.close();
}

7.2 Reading files 

Function description: read the contents of the file into the program

Although we have implemented the operation of saving to a file after adding employees, but every time the program starts to run, the data in the file is not read into the program, and our program function still needs to clear the file. Therefore, there are three situations in which the constructor initializes data:

1. The first use, the file is not created

2. The file exists, but the data is cleared by the user

3. The file exists and saves all employee data

7.1.1 File not created

Add a new member attribute m_FilelsEmpty in workerManager.h to mark whether the file is empty, and write the following code in the constructor WorkerManager::WorkerManager()

//1.文件不存在
	ifstream ifs;
	ifs.open(FILENAME, ios::in);//读文件
	if (!ifs.is_open())
	{
		cout << "文件不存在" << endl;
		//初始化属性
		this->m_EmpNum = 0;
		this->m_Emparray = NULL;
		this->m_FilelsEmpty = true;
		ifs.close();
		return;
	}

 7.1.2 The file exists but the data is empty

//2.文件存在 数据为空
	char ch;
	ifs>> ch;
	if (ifs.eof())
	{
		cout << "文件为空" << endl;
		//初始化属性
		this->m_EmpNum = 0;
		this->m_Emparray = NULL;
		this->m_FilelsEmpty = true;
		ifs.close();
		return;
	}

7.1.3 The file exists and has data

Add member function int get_EmpNum() in workerManager.h; 

Implemented in workerManager.cpp.

First you need to re-read the information in the file. Read the number of people in the file, define a function get_empnum() to read the number of people in the file, you can read lines through the getline() function, and each line represents a person.

//统计文件中的人数
int WorkerManager::get_empnum()
{
	ifstream ifs;
	ifs.open(FILENAME, ios::in);//打开文件 读文件
	string buf;
	int count=0;
	while (getline(ifs,buf))
	{
		count++;
	}
	return count;
}

 At this point, the third case can be realized in the WorkerManager() constructor, the file exists and has data. And also update the number of people in m_EmpNum.

//3.文件存在,并且有数据
	int num = this->get_empnum();
	cout << "职工的人数为:" << num << endl;
	this->m_EmpNum = num;

 7.3 Initializing arrays

Add a member function in WorkerManager.h: void init_Emp() is used to initialize the array, the purpose is to let the program read the data of the existing file when there is existing file data, and load it as the initial data.

//初始化职工(为了让程序读取已有文件的数据,把它加载出来作为初始数据)
void WorkerManager::init_Emp()
{
	ifstream ifs;
	ifs.open(FILENAME, ios::in);
	int id;
	string name;
	int did;
	int count=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 if (did == 3)
		{
			worker = new boss(id, name, did);
		}
		this->m_Emparray[count] = worker;
		count++;
	}
	//关闭文件
	ifs.close();
}

8. Show employees

Function: Display all current employee information.

Add the member function void show_Emp() in workerManager.h; Write the implementation of the function in workerManager.cpp, first judge whether the file is empty, and call the display personal information function: perinf() if it is not empty.

//显示职工
void WorkerManager::show_emp()
{
	//判断文件是否为空
	if (this->m_FilelsEmpty)
	{
		cout << "文件不存在" << endl;
	}
	else 
	{
		for (int i = 0; i < this->m_EmpNum; i++)
		{
			//利用多态调用程序接口
			this->m_Emparray[i]->perinf();
		}
	}
	system("pause");
	system("cls");
}

9. Delete employees 

Function description: delete employees according to their numbers.

        Add a member function in workerManager.h Add a member function void Del_Emp( ) in workerManager.h; first judge whether the file exists, and if it exists, judge whether the input employee number exists. Next, add the member function int ifexit(int id) in workerManager.h; write the implementation in workerManager.cpp, if the int index exists, return the position in the employee array, and return -1 if it does not exist. Finally return index;

//判断职工是否存在
int WorkerManager::ifexit(int id)
{
	int index = -1;
	for (int i = 0; i < this->m_EmpNum; i++)
	{
		if (this->m_Emparray[i]->m_id == id)
		{
			index = i;
			break;
		}
	}
	return index;
}

        Write the implementation of the delete function Del_Emp() in workerManager.cpp. After judging whether the above file is empty and whether the input employee exists, if it exists, delete it, and use data forward overwriting as deletion. Finally, the number of people in the array must be updated, and the data will be updated to the file synchronously.

//删除职工
void WorkerManager::Del_Emp()
{
	if (this->m_FilelsEmpty)
	{
		cout << "文件为空" << endl;
	}
	else
	{
		int id = 0;
		cout << "请输入要删除的员工编号:";
		cin >> id;
		int index = this->ifexit(id);
		if (index == -1)
		{
			cout << "职工不存在" << endl;
		}
		else
		{
			//做数据前移覆盖作为删除
			for (int a = index; a < this->m_EmpNum-1; a++)
			{
				this->m_Emparray[a] = this->m_Emparray[a + 1];
			}
			cout << "删除成功" << endl;
			this->m_EmpNum--;//更新数组中的人员数
			this->save();//数据同步更新到文件中
		}
	}
	system("pause");
	system("cls");
}

10. Modify employees

        Add the function of modifying workers in workerManager.h, void mod_emp(); Write the implementation in workerManager.cpp. Still the same, first determine whether the file is empty, enter the employee number to be modified, and then determine whether the employee exists. Finally, the number of people in the array is updated, and the data is updated to the file synchronously.

//修改职工
void WorkerManager::mod_emp()
{
	if (this->m_FilelsEmpty)
	{
		cout << "文件为空" << endl;
	}
	else
	{
		cout << "请输入需要修改的职工编号" << endl;
		int id;
		cin >> id;
		int ret = this->ifexit(id);
		if (ret == -1)
		{
			cout << "查无此人" << endl;
		}
		else
		{
			delete this->m_Emparray[ret];
			int newid = 0;
			string newname="";
			int newdid = 0;
			cout << "请输入新的ID号:";
			cin >> newid;
			cout << "请输入新的姓名:";
			cin >> newname;
			cout << "请输入新的岗位(1.职工 2.经理 3.老板):";
			again:cin >> newdid;
			worker* wk = NULL;
			switch (newdid)
			{
			case 1:
				wk = new employee(newid, newname, 1);
				break;
			case 2:
				wk = new manager(newid, newname, 2);
				break;
			case 3:
				wk = new boss(newid, newname, 3);
				break;
			default:
				cout << "非法输入请重新输入" << endl;
				goto again;
				break;
			}
			//更新数据到数组中
			this->m_Emparray[ret] = wk;
			cout << "修改成功!" << endl;
			//保存文件
			this->save();
		}
	}
	system("pause");
	system("cls");
}

11. Find employees

        Find employee function void fine_emp(); Provide two search methods: 1. Search by employee number. 2. Search by employee name. Still the same, first determine whether the file is empty, enter the employee number or name to be searched, and then determine whether the employee exists, and finally call the perinf() function to display the employee. Here the switch selection statement is used to determine which search method it is. Use loop traversal to find whether the number or name exists. Here I use a goto command in the default, in order to return and reselect the search method after a mistaken input.
 

//查找员工
void WorkerManager::fine_emp()
{
	if (this->m_FilelsEmpty)
	{
		cout << "文件为空" << endl;
	}
	else
	{
		cout << "请输入要查找的方式" << endl;
		cout << "1.按职工编号查找" << endl;
		cout << "2.按职工姓名查找" << endl;
		cout << "请输入:";
		int a = 0;
		again:cin >> a;
		switch (a)
		{
			case 1:
			{
				cout << "请输入需要修改的职工编号: ";
				int id;
				cin >> id;
				int ret = this->ifexit(id);
				if (ret == -1)
				{
					cout << "查无此人" << endl;
				}
				else
				{
					this->m_Emparray[ret]->perinf();
				}
				break;
			}
			case 2:
			{
				cout << "请输入需要修改的职工姓名: ";
				string name;
				cin >> name;
				bool flag = false;
				for (int i = 0; i < this->m_EmpNum; i++)
				{
					if (name == this->m_Emparray[i]->m_name)
					{
						this->m_Emparray[i]->perinf();
						flag = true;
					}
				}
				if (flag == false)
				{
					cout << "查无此人" << endl;
				}
				break;
			}
			default:
				cout << "非法输入请重新输入" << endl;
				goto again;
		}
	}
	system("pause");
	system("cls");
}

12. Sorting 

Function description: Sort by employee number.

A selection sorting algorithm is used here, assuming an array number with the largest (minimum) ID number, traverse all the ID numbers of the array and its size, if there is a larger (smaller) ID number, exchange the serial number. Finally save the file.

//对编号排序
void WorkerManager::sort_emp()
{
	if (this->m_FilelsEmpty)
	{
		cout << "文件为空" << endl;
	}
	else
	{
		cout << "请输入排序的方式" << endl;
		cout << "1.按职工编号升序" << endl;
		cout << "2.按职工编号降序" << endl;
		cout << "请输入:";
		int a = 0;
		again:cin >> a;
		switch (a)
		{
		case 1:
		{
			for (int i = 0; i < m_EmpNum; i++)
			{
				int min = i;
				for (int j = i + 1; j < m_EmpNum; j++)
				{
					if (m_Emparray[min]->m_id > m_Emparray[j]->m_id)
					{
						min = j;
					}
				}
				if (min != i)
				{
					worker* temp = this->m_Emparray[i];
					this->m_Emparray[i] = this->m_Emparray[min];
					this->m_Emparray[min] = temp;
				}
			}
			break;
		}
		case 2:
		{
			for (int i = 0; i < m_EmpNum; i++)
			{
				int max = i;
				for (int j = i + 1; j < m_EmpNum; j++)
				{
					if (m_Emparray[max]->m_id < m_Emparray[j]->m_id)
					{
						max = j;
					}
				}
				if (max != i)
				{
					worker* temp = this->m_Emparray[i];
					this->m_Emparray[i] = this->m_Emparray[max];
					this->m_Emparray[max] = temp;
				}
			}
			break;
		}
		default:
			cout << "非法输入请重新输入:" ;
			goto again;
	}
	cout << "排序成功" << endl;
	this->save();
	}
    system("pause");
	system("cls");
}

Thirteen, clear the file

 When clearing the file, the memory needs to be freed, the pointer is set to empty, and the number is set to 0.

//清空文件
void WorkerManager::clean_file()
{
	cout << "是否确定清空文件(1.是 0.否):" ;
	int select = 0;
	cin >> select;
	if (select == 1)
	{
		//清空文件
		ofstream ofs(FILENAME, ios::trunc);//删除文件后重新创建
		ofs.close();
		if (this->m_Emparray != NULL)
		{
			//删除堆区的每个职工对象
			for (int i = 0; i < this->m_EmpNum; i++)
			{
				delete this->m_Emparray[i];
				this->m_Emparray[i] = NULL;

			}
			//删除堆区数组指针
			delete[]this->m_Emparray;
			this->m_Emparray = NULL;
			this->m_EmpNum = 0;
			this->m_FilelsEmpty=true;
		}
		cout << "清空成功" << endl;
	}
	system("pause");
	system("cls");
}

Attach the declaration from the workerManager.h header file.

#pragma once
#include<iostream>
using namespace std;
#include "worker.h"
#include"job.h"
#include<fstream>
#include<string>
#define FILENAME "empfile.txt"
class WorkerManager
{
public:
	//构造函数
	WorkerManager();
	//菜单
	void menu();
	//记录职工人数
	int m_EmpNum;
	//职工数组指针
	worker** m_Emparray;
	//1.添加职工
	void add_emp();
	//保存文件
	void save();
	//判断文件是否为空 
	bool m_FilelsEmpty;
	//统计文件中的人数
	int get_empnum();
	//初始化职工
	void init_Emp();
	//显示职工
	void show_emp();
	//删除职工
	void Del_Emp();
	//判断职工是否存在
	int ifexit(int id);//存在返回职工数组中的位置,不存在返回-1
	//修改职工
	void mod_emp();
	//查找员工
	void fine_emp();
	//对编号排序
	void sort_emp();
	//清空文件
	void clean_file();
	//析构函数
	~WorkerManager();
};

Finally, attach the test code of test.cpp containing the main() function 

#include<iostream>
using namespace std;
#include"workerManager.h"
#include"worker.h"
#include"job.h"
int main()
{
	//调用菜单成员函数
	int ret = 0;
	while (1)
	{
		wm.menu();
		cout << "请输入您的选择:" ;
		cin >> ret;
		switch (ret)
		{
		case 0://退出系统
			return 0;
			break;
		case 1://添加职工
			wm.add_emp();
			break;
		case 2://显示职工
			wm.show_emp();
			break;
		case 3://删除离职职工
			wm.Del_Emp();
			break;
		case 4://修改职工
			wm.mod_emp();
			break;
		case 5://查找职工
			wm.fine_emp();
			break;
		case 6://按照编号排序
			wm.sort_emp();
			break;
		case 7://清空所有文档
			wm.clean_file();
			break;
		default:
			cout << "非法输入请重新输入" << endl;
			system("pause");
			system("cls");
			break;
		}
	}
	system("pause");
	return 0;
}

Summarize

        This project uses C++ encapsulation, inheritance, polymorphism and file writing and reading. The key points are: Create a secondary pointer of worker** to maintain the pointers of all employees in an array. In the constructor, the file is initialized according to whether the file exists and whether there is data in the file. If there is data, you need to read the data in the file as the initial data.        

Guess you like

Origin blog.csdn.net/m0_74893211/article/details/131107964