从文件中读取数组并将它们存储到结构成员中

Read in arrays from a files and store them into struct members

假设我有这样的结构:

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()?

我建议重载 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);
}

您的字段是 space 分隔的,因此您不需要使用 getline。字符串的 operator>> 会一直读到白色 space 字符。