在数据库文件中创建10条空白记录

Creating 10 blank records in a database file

本文关键字:10条 空白 记录 创建 数据库 文件      更新时间:2023-10-16

我正在使用for循环来尝试创建一个由10条记录组成的"空白"文件,其中使用类中的构造函数将值设置为0或空白,如下所示:

class employee {
char name[30], hire_date[30], salary[30];
int ID;
public:
employee(string = "", int = 0, string = "", string = "") {
void setHireDate(string);
string getHireDate();
void setname(string);
string getName();
void setsal(string);
string getsal();
void setId(int);
int getId();
}

见下文int main()的开头。我的程序应该在其中创建空白数据库文件的部分

int main()
{
int a, id;
string name, hire_date, salary;
cout << "Welcome to Mahendra Pruitt's Employee Database!nEnter a number for the option you would like to select:nPlease choose option 0 if you haven't already chosen that one.n" <<
"0 - Create a blank new database file that will overwrite all existing data." << endl
<< "1 - Choose employee IDs (1-10) and change or add information to their file" << endl
<< "2 - Select whether or not you would like to update, view, or add a new record." << endl;
cin >> a;

// creating a blank database file
employee blankelist;
if (a == 0) {
while (a == 0) {
if (a == 0) {

ofstream outdatabase("database.dat", ios::out | ios::binary);
for (int i = 0; i < 10; i++) {
outdatabase.write(reinterpret_cast <const char *> (&blankelist), sizeof(employee));
}
cout << "Enter the number 1 or 2: " << endl
<< "1 - Choose employee IDs (1-10) and change or add information to their file" << endl
<< "2 - Select whether or not you would like to update, view, or add a new record." << endl;
cin >> a;
}
}
}

在我的程序的其余部分中,我使用了一个单独的雇员实例,我称之为"employed"。。。请参阅我的一个函数的示例,其目的是输出要查看的存储信息:

void outputLine(ostream &output, employee &employed, int i, fstream &readfromfile)
{
int id = i;
readfromfile.seekg((id - 1) * sizeof(employee));
readfromfile.read(reinterpret_cast <char *>(&employed), sizeof(employee));
output << "ID: " << employed.getId() << endl
<< "Name: " << employed.getName() << endl
<< "Salary: " << employed.getsal() << endl
<< "Hire date: " << employed.getHireDate() << endl;
}

当我运行创建这些空白文件的选项并尝试查看记录时,它会显示数字/胡言乱语。。。见以下输出:

Enter your choice:
1 - Update an account
2 - Add a new account
3 - View record
4 - End program
3
Which record would you like to view? (1-10). Enter 0 to go back to the menu.:
1
ID: -858993460
Name:  ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
Salary: ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
Hire date: 
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠

我如何让我的程序设置它,以便每当我运行创建空白记录的部分时,它都会创建这些记录,如果我试图查看记录,它会显示为空白?

我也尝试过以下语句:

outdatabase.write(reinterpret_cast <const char *> (&employed), sizeof(employee));

而不是

outdatabase.write(reinterpret_cast <const char *> (&blankelist), sizeof(employee));

在我的for循环中,但这也不起作用。

期待您的回复!

在构造函数employee::employee()中,您正在声明一些函数,而不是调用它们。您似乎需要调用一些成员函数,这些函数应该将成员设置为合理的值。

顺便说一句,您应该学习针对此类任务的类的序列化和反序列化。

进一步读数:

  • 序列化和非序列化,C++常见问题解答-ISO C++
  • C++序列化实用指南
  • Boost序列化
  • MFC中的序列化