代码之家  ›  专栏  ›  技术社区  ›  Anonymous

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

  •  0
  • Anonymous  · 技术社区  · 7 年前

    我的文本文件名为“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;
        }
    };
    

    我的主要。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 回复  |  直到 7 年前
        1
  •  -1
  •   Islam Hassan    7 年前

    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 如果不是这样的话。

        2
  •  -1
  •   Shahi Papon    7 年前

    对直接的方法可以帮助你,否则你可以使用简单的方法,如。。。

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

    然后你可以调用你的方法。但直接的方法比这更完美:)