1

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

45678 25 86400 Doe, John A.

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

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

3 回答 3

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;
}
于 2012-12-05T20:55:56.223 回答
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.
}
于 2012-12-05T21:22:14.233 回答
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
    }
}
于 2012-12-05T21:24:34.613 回答