我正在尝试从文件中读取并根据输入的员工编号搜索特定记录。我已经编写了代码,但每次我搜索已经存在的记录时,我都会收到未找到的消息记录。任何人都可以指出错误。 我的代码是:
#include <iostream>
#include <fstream>
using namespace std;
class emp
{
int empno;
char name[20];
char dept[10];
float salary;
public:
void getdata()
{
cout << "Enter the employee number " << endl;
cin >> empno;
cout << "Enter the name : " << endl;
cin >> name;
cout << "Enter the department of the employee : " << endl;
cin >> dept;
cout << "Enter the salary of the employee : " <<endl;
cin >> salary;
}
void display()
{
cout << "Emp No : " <<empno;
cout << endl << "Name : " << name << endl << "Department : " <<dept <<endl
<<"Salary : " << salary <<endl;
}
int getempno()
{
return empno;
}
};
int main()
{
emp obj1;
int eno;
char ch = 'n';
ifstream file1("emp.txt", ios:: in); // this file should already exist
cout << "Enter the employee number to be searched for : " <<endl;
cin >> eno;
while(!file1.eof())
{
file1.read((char *)&obj1, sizeof(obj1));
if(obj1.getempno()==eno)
{
obj1.display();
ch = 'y';
break;
}
}
if(ch =='n')
cout << "Record Not Found !!" << endl;
file1.close();
}
我在main函数中使用变量eno并将eno与函数getempno返回的empno进行比较。如果它相等,我调用成员函数显示但显示功能不起作用。我只收到未找到的消息记录。
答案 0 :(得分:2)
以标题中所述的二进制文件打开流:
ifstream file1("emp.txt", ios:: in | ios::binary); // binary
并且还要更改循环,以便在没有先读取的情况下不对eof()进行测试:
while (file1.read((char *)&obj1, sizeof(obj1)))
我可以通过生成一个用ios :: binary set编写的快速脏的二进制文件来成功测试这个更新的代码(我不在这里放置构造函数代码):
void produceTest(string file) {
ofstream os(file, ios::out | ios::binary);
emp a(1, "Durand", "IT", 1234.30);
emp b(2, "Dupond", "Finance", 1530.20);
emp c(25, "Chris", "MD", 15.30);
os.write(reinterpret_cast<char*>(&a), sizeof(emp));
os.write(reinterpret_cast<char*>(&b), sizeof(emp));
os.write(reinterpret_cast<char*>(&c), sizeof(emp));
}
如果它不起作用,则问题在于您的文件。例如,潜在的问题可能是: