从文件中读取数据并将其存储在变量中

Reading data from a file and storing it in a variable

本文关键字:存储 变量 文件 读取 数据      更新时间:2023-10-16

我想从一个名为organisation.txt的文本文件中显示员工编号(不在类中声明)、姓名、职业和部门,并将它们保存在类OrganisationRecord中声明的变量中。

如何提取文本文件中的数据并将其保存到相应的变量中?

#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;
}

组织.txt

0001 
Stephen Jones 
Sales Clerk 
Sales
0002 
John Smith 
Programmer 
OS Development
0003 
Fred Blogs 
Project Manager 
Outsourcing

这是一种无需对输入进行任何错误检查即可工作的方法。 就像其他人说的那样,您需要使用std::getline()逐行读取文件,因为直接输入变量会导致输入解析由文本中的空格分隔,而不是整行。

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);
}