我有一個文件,其中包含每行(id,部門,工資和名稱)上的員工信息。下面是一個例子行:分解來自文件的輸入C++
45678 25 86400 Doe, John A.
現在我使用fstream的,其工作,直到我得到的名稱部分讀每個詞。我的問題是整個捕捉這個名字的最簡單方法是什麼?
Data >> Word;
while(Data.good())
{
//blah blah storing them into a node
Data >> Word;
}
我有一個文件,其中包含每行(id,部門,工資和名稱)上的員工信息。下面是一個例子行:分解來自文件的輸入C++
45678 25 86400 Doe, John A.
現在我使用fstream的,其工作,直到我得到的名稱部分讀每個詞。我的問題是整個捕捉這個名字的最簡單方法是什麼?
Data >> Word;
while(Data.good())
{
//blah blah storing them into a node
Data >> Word;
}
你可能要定義一個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.
}
這工作完美,並且非常有意義!謝謝。 – sharkman
#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;
}
這個'getline'很好! (但'忽略'不是很好..) –
我會創建記錄並定義輸入運算符
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
@shep:'while(Data >> Word){/ * Do Stuff * /}' –