【发布时间】:2014-02-06 07:41:11
【问题描述】:
我有一个关于我的任务的问题。
这里我有两个类,员工类和通用类
void GM::addEmployee(fstream& afile, int noOfRecords)
{
afile.open("EmployeeInfo.dat", ios::in | ios::binary);
employee::eInfo e;
employee emp;
char name[80];
cout << "\nAdd Employee Info" << endl;
cout << "---------------------" << endl;
cout << "New Employee Username: ";
cin.clear();
cin.ignore(100, '\n');
cin.getline(name, 80);
//Check if there is already an entry inside the file with this name.
//If yes, add fail
bool flag = true;
if(noOfRecords > 0)
{
for(int i=1; i<=noOfRecords; i++)
{
afile.read (reinterpret_cast <char *>(&e), sizeof(e));
if(!strcmp(name, e.username))
{
cout << "Username is used, add GM failed" << endl;
flag = false;
}
}
}
afile.close();
if(flag)
{
//open in appending mode
afile.open("EmployeeInfo.dat", ios::out | ios::app | ios::binary);
strcpy(e.username, name);
cout << "Please Enter New Employee's Password: ";
cin.getline(e.password, 80);
cout << "\nPlease Enter New Employee's Appointment "
<< "\n(0 = GM / 1 = HM / "
<< "2= BS / 3 = FOS)\n : ";
cin >> e.eid;
cin.clear();
cin.ignore(100, '\n');
emp.dist = strlen(e.password);
emp.caesar_encrypt(e.password, 3, emp.dist);
afile.write(reinterpret_cast <const char *>(&e), sizeof(e));
afile.close();
cout << "\nEmployee Added" << endl;
}
}
以上是我的GM类的一个函数,就是添加员工。
我已将员工类中的结构声明为
struct eInfo
{
char username [80];
char password [80];
int eid;
};
这种做法的问题在于,当我尝试添加员工时 我的 EmployeeInfo.dat 数据消失了。使用添加员工功能后,所有内容都变为空白。
谁能指导我做错了什么?
【问题讨论】:
标签: c++ function class struct fstream