2012-12-05 50 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 
    } 
}