从文件c ++中分解输入

时间:2012-12-05 20:30:03

标签: c++ fstream

我有一个文件,其中包含每行的员工信息(ID,部门,工资和姓名)。这是一个示例行:

45678 25 86400 Doe, John A.

现在我正在使用fstream读取每个单词,直到我到达名称部分。我的问题是,从整体上捕获该名称的最简单方法是什么?

Data >> Word;
while(Data.good())
{
    //blah blah storing them into a node
    Data >> Word;
}

3 个答案:

答案 0 :(得分:1)

#include <fstream>
#include <iostream>
int main() {
  std::ifstream in("input");
  std::string s;
  struct Record { int id, dept, sal; std::string name; };
  Record r;
  in >> r.id >> r.dept >> r.sal;
  in.ignore(256, ' ');
  getline(in, r.name);
  std::cout << r.name << std::endl;
  return 0;
}

答案 1 :(得分:1)

您可能希望定义struct来保存员工的数据,定义operator>>的重载以从您的文件中读取其中一条记录:

struct employee { 
    int id;
    int department;
    double salary;
    std::string name;

    friend std::istream &operator>>(std::istream &is, employee &e) { 
       is >> e.id >> e.department >> e.salary;
       return std::getline(is, e.name);
    }
};

int main() { 
    std::ifstream infile("employees.txt");

    std::vector<employee> employees((std::istream_iterator<employee>(infile)),
                                     std::istream_iterator<employee>());

    // Now all the data is in the employees vector.
}

答案 2 :(得分:0)

我会创建一个记录并定义输入操作符

class Employee
{
    int id;
    int department;
    int salary;
    std::string name;

    friend std::istream& operator>>(std::istream& str, Employee& dst)
    {
        str >> dst.id >> dst.department >> dst.salary;
        std::getline(str, dst.name); // Read to the end of line
        return str;
    }
};

int main()
{
    Employee  e;
    while(std::cin >> e)
    {
         // Word with employee
    }
}