1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.