我对我的任务有疑问。
这里有2个类,员工类和gm类
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数据消失了。使用添加员工功能后,一切都变得空白。
谁能指导我做错了什么?
答案 0 :(得分:0)
这是将数据读入e
的错误方法:
afile.read(reinterpret_cast<char*>(&e), sizeof(e));
同样,这是从e
写入数据的错误方法:
afile.write(reinterpret_cast<const char*>(&e), sizeof(e));
如果您需要打印或阅读e
的数据成员,则需要一次执行此操作。此外,在此上下文中使用read
/ write
是不必要的,因为您只需使用提取器和插入器:
afile >> e.username; // ... afile << e.username << e.password;