假設我有一個這樣的結構:
struct Person
{
string fName;
string lName;
int age;
};
我想讀入這樣的檔案(ppl.log):
Glenallen Mixon 14
Bobson Dugnutt 41
Tim Sandaele 11
我將如何讀取檔案并存盤它們?這就是我所擁有的
int main()
{
Person p1, p2, p3;
ifstream fin;
fin.open("ppl.log");
fin >> p1;
fin >> p2;
fin >> p3;
return 0;
}
整行都是這樣嗎?或者我必須使用 getline() 嗎?
uj5u.com熱心網友回復:
我建議多載operator>>:
struct Person
{
string fName;
string lName;
int age;
friend std::istream& operator>>(std::istream& input, Person& p);
};
std::istream& operator>>(std::istream& input, Person& p)
{
input >> p.fName;
input >> p.lName;
input >> p.age;
input.ignore(10000, '\n'); // Align to next record.
return input;
}
這允許您執行以下操作:
std::vector<Person> database;
Person p;
//...
while (fin >> p)
{
database.push_back(p);
}
您的欄位以空格分隔,因此您無需使用getline. 該operator>>字串將讀到一個空白字符。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/329553.html
上一篇:R:如果在相應的行中沒有找到某個數字,則列印ID值。
下一篇:這個程式怎么做,但反過來,模式
