[英]Read text file into class member variables using getline - c++
我最近开始学习c ++,所以我仍在学习。 基本上,我尝试在找到字符串“ NEW_EMPLOYEE”时读取文本文件,然后将每一行存储到其各自的成员变量中,直到在文本文件中找到空行以停止。 我遇到的问题是如何使用getline一次将每一行都导入到“ Employee”类的每个变量中? 我应该改用istringstream吗?
我的文本文件名为“ employee.txt”
NEW_EMPLOYEE
460713
John
Smith
64000
36
END_OF_FILE
我班的员工:
class Employee {
private: //Member variables
int ID;
string FirstName;
string LastName;
int Salary;
int Hours;
public:
Employee() {} //Default constructor
Employee(int& id, string& firstName, string& lastName, int& salary, int& hours) {
ID = id;
FirstName = firstName;
LastName = lastName;
Salary = salary
Hours = hours;
}
};
我的main.cpp:
#include <iostream>
#include <fstream>
int main() {
Employee employee;
int id;
string firstName;
string lastName;
int salary;
int hours;
string line;
ifstream employeeFile;
employeeFile.open("employee.txt");
while(getline(employeeFile, line)) {
if(line == "NEW_EMPLOYEE") {
do {
//Don't know what to do here???
} while (!line.empty());
}
}
employeeFile.close();
return 0;
}
直接的方法是做类似的事情
while(employeeFile >> line){
if(line != "NEW_EMPLOYEE") continue;
int id,salary,hours;
string firstName, lastName;
employeeFile >> id >> firstName >> lastName >> salary >> hours;
Employee employee = Employee(id, firstName, lastName, salary, hours);
// Do what you want with employee
}
这假定数据始终以相同的顺序写入文件。 我还假定行不包含空格,因为它们是数字或名称,因此我使用了>>
运算符。 如果不是这种情况,可以改用getline
。
如果您始终确保数据顺序相同,那么这就足够了。 如果不正确,建议您将对象作为JSON写入文件中,并使用JSON解析器库将文件直接读取到对象中。
是的..直截了当的方法可以帮助您,否则您可以使用简单的方法,例如...
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <sstream>
using namespace std;
int main() {
string x[100];
int i=0;
// Employee employee;
int id;
string firstName;
string lastName;
int salary;
int hours;
string line;
string text;
ifstream employeeFile;
employeeFile.open("employee.txt");
while(!employeeFile.eof())
{
getline(employeeFile,text);
x[i++]=text;
}
// employeeFile.close();
stringstream(x[1]) >> id; //string to int
firstName = x[2];
lastName = x[3];
stringstream(x[4]) >> salary;
stringstream(x[5]) >> hours;
//cout<<id<<" "<<firstName;
}
然后,您可以调用您的方法。 但是简单的方法比这更完美:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.