2012-12-05 132 views
1

我有一个文件,其中包含每行(id,部门,工资和名称)上的员工信息。下面是一个例子行:分解来自文件的输入C++

45678 25 86400 Doe, John A. 

现在我使用fstream的,其工作,直到我得到的名称部分读每个词。我的问题是整个捕捉这个名字的最简单方法是什么?

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

唉!没有!这不是如何从循环中的iostream读取! –

+0

@LightnessRacesinOrbit,更好的建议? – Shep

+1

@shep:'while(Data >> Word){/ * Do Stuff * /}' –

回答

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. 
} 
+0

这工作完美,并且非常有意义!谢谢。 – sharkman

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; 
} 
+0

这个'getline'很好! (但'忽略'不是很好..) –

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