fsfh60
fsfh60

Reputation: 61

Could you please verify if my code is correct for saving string to struct?

I am trying to file input information from a .txt file that has three inputs i.e(Mike Jones 60) and inserting them into a structure C++ to use for my output to screen.

struct Person {
    string name;
    int age;
};
void addData()
{
    Person aPerson;
    char fileName[80];
    cout << "Please enter the file name: ";
    cin.getline(fileName, 80);
    //string fullName;
    ifstream fin(fileName);
    string tmp;
    stringstream ss;
    while (!fin.eof()) {
        getline(fin, aPerson.name);
        aPerson.name = tmp;
        getline(fin, tmp);
        ss << tmp;
        ss >> aPerson.age;
        ss.clear();
        getline(fin, tmp);
        ss.clear();
        cout << aPerson.name << aPerson.age << endl;
    }
}

Upvotes: 0

Views: 78

Answers (1)

Jack Deeth
Jack Deeth

Reputation: 3357

This code will read data in this format:

Joe Bloggs
42

Franziska von Karma
23

Jeff Jefferson
84

Is that what your input data looks like?

If it's one line per person, and each person has exactly two words in their name, you can use the third parameter of getline to set a custom delimiter - instead of reading the whole line, it will read until it gets to a space.

Joe Bloggs 42
Jeff Jefferson 84
Amy Anderson 57

To process this data:

…
while (!fin.eof()) {
  string firstname;
  getline(fin, firstname, ' ');
  string surname;
  getline(fin, surname, ' ');
  aPerson.name = firstname + " " + surname;
  string age;
  getline(fin, age);
  ss << age;
  ss >> aPerson.age;
  cout << aPerson.name << aPerson.age << endl;
  ss.clear();
}

If you can get the data in Comma-Separated Data format, or tab-separated, or anything-that's-not-a-space-separated, you can use that delimiter and extract the data in two steps not three.

Upvotes: 1

Related Questions