fsfh60 fsfh60 - 1 year ago 76
C++ Question

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;
getline(fin, tmp);
cout << aPerson.name << aPerson.age << endl;

Answer Source

This code will read data in this format:

Joe Bloggs

Franziska von Karma

Jeff Jefferson

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;

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download