我想从名为organisation.txt
的文本文件中显示员工编号(不在课堂上声明),姓名,职业和员工部门,并将其保存在课程中声明的变量{ {1}}。
如何提取文本文件中的数据并将其保存到相应的变量中?
OrganisationRecord
organisation.txt
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#define ORGANISATIONALRECORDSFILE "organisation.txt"
#define HRRECORDSFILE "HR_records.txt"
#define PAYROLLRECORDSFILE "payroll_records.txt"
using namespace std;
class OrganisationRecord
{
private:
public:
string name;
string occupation;
string department;
};
class HRRecord
{
private:
public:
string address;
string phonenumber;
string ninumber;
};
class PayrollRecord
{
private:
public:
string ninumber;
double salary;
};
class PayrollProcessing
{
private:
ifstream inputfile;
ofstream outputfile;
vector<OrganisationRecord> OrganisationRecords;
vector<HRRecord> HRRecords;
vector<PayrollRecord> PayrollRecords;
public:
void loadOrganisationRecords(string filename);
void loadHRRecords(string filename);
void loadPayrollRecords(string filename);
void displayEmployeeOfSalaryGTE(double salary);
//GTE = greater than or equal to
};
void PayrollProcessing::loadOrganisationRecords(string filename)
{
inputfile.open(ORGANISATIONALRECORDSFILE);
if (!inputfile)
{
cout << "the organisation records file does not exist" << endl;
return;
}
OrganisationRecord _organisationrecord;
int employeenumber;
while (inputfile >> employeenumber)
{
while (inputfile >> _organisationrecord.name)
{
cout << _organisationrecord.name;
cout << _organisationrecord.occupation;
cout << _organisationrecord.department <<endl;
}
OrganisationRecords.push_back(_organisationrecord);
}
}
int main(void)
{
PayrollProcessing database1;
database1.loadOrganisationRecords(ORGANISATIONALRECORDSFILE);
return 0;
}
答案 0 :(得分:0)
这是一种无需对输入进行任何错误检查即可使用的方法。就像其他人所说的那样,你需要使用std::getline()
逐行读取文件,因为直接输入你的变量会导致输入解析被文本中的空格分隔,而不是整行。 / p>
OrganisationRecord _organisationrecord;
std::string employeeNumberStr;
int employeenumber;
// without any robust error checking...
while (std::getline(inputfile, employeeNumberStr))
{
// store employee number string as an integer
std::stringstream ss;
ss << employeeNumberStr;
ss >> employeenumber;
std::getline(inputfile, _organisationrecord.name);
std::getline(inputfile, _organisationrecord.occupation);
std::getline(inputfile, _organisationrecord.department);
// debug print results
std::cout << "id number: " << employeenumber << std::endl;
std::cout << "name: " << _organisationrecord.name << std::endl;
std::cout << "occupation: " << _organisationrecord.occupation << std::endl;
std::cout << "department: " << _organisationrecord.department << std::endl;
OrganisationRecords.push_back(_organisationrecord);
}