C++ 将输入从文件c++;

C++ 将输入从文件c++;,c++,fstream,C++,Fstream,我有一个文件,每行都包含员工信息(id、部门、工资和姓名)。下面是一行示例: 45678 25 86400 Doe, John A. 现在,我正在使用fstream阅读每个单词,它一直工作到我找到名称部分。我的问题是,什么是最简单的方法来获取这个名字作为一个整体 Data >> Word; while(Data.good()) { //blah blah storing them into a node Data >> Word; } #包括 #包括

我有一个文件,每行都包含员工信息(id、部门、工资和姓名)。下面是一行示例:

45678 25 86400 Doe, John A.
现在,我正在使用fstream阅读每个单词,它一直工作到我找到名称部分。我的问题是,什么是最简单的方法来获取这个名字作为一个整体

Data >> Word;
while(Data.good())
{
    //blah blah storing them into a node
    Data >> Word;
}
#包括
#包括
int main(){
std::ifstream in(“输入”);
std::字符串s;
结构记录{int-id,dept,sal;std::string-name;};
记录r;
在>>r.id>>r.dept>>r.sal;
忽略(256,);
getline(in,r.name);

std::cout您可能希望定义一个
结构来保存员工的数据,定义一个
操作符>>
重载来从您的文件中读取其中一条记录:

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.
}
struct employee{
int-id;
国际部;
双薪;
std::字符串名;
friend std::istream&operator>>(std::istream&is,员工与e){
is>>e.id>>e.department>>e.salary;
返回std::getline(is,e.name);
}
};
int main(){
std::ifstream infle(“employees.txt”);
std::vector employees((std::istream_迭代器(infle)),
std::istreamu迭代器();
//现在所有数据都在employees向量中。
}

我将创建一个记录并定义输入运算符

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

啊!不!这不是在循环中读取iostream的方法!@LightnessRacesinOrbit,更好的建议?@shep:
while(Data>>Word){/*DoStuff*/}
getline
很好!(但是
ignore
没有那么好……)
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
    }
}