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

Time:10-22

Suppose I have a struct like this:

struct Person
{
  string fName;
  string lName;
  int age;
};

And I want to read in a file(ppl.log) like this:

Glenallen Mixon 14
Bobson Dugnutt 41
Tim Sandaele 11

How would I read in the file and store them? This is what I have

int main() 
{
  Person p1, p2, p3;
  ifstream fin;
  fin.open("ppl.log");
  fin >> p1;
  fin >> p2;
  fin >> p3;

  return 0;
}

Does that read in the entire line? Or do I have to use the getline()?

CodePudding user response:

I recommend overloading 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;
}

This allows you to do things like this:

std::vector<Person> database;
Person p;
//...
while (fin >> p)
{
    database.push_back(p);
}

Your fields are space separated, so you don't need to use getline. The operator>> for strings will read until a whitespace character.

  • Related