使用getline - c ++将文本文件读入类成员变量

时间:2017-09-23 21:38:56

标签: c++ class ifstream istringstream

我最近开始学习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;
}

2 个答案:

答案 0 :(得分:-1)

直截了当的做法是做那样的事情

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解析器库将文件直接读入对象。

答案 1 :(得分:-1)

是的..直接前进的方法可以帮助你,否则你可以使用简单的方法,如...

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



}

然后你可以打电话给你的方法。但直接的方法比这更完美:)