Hi I wish to break up a date entered as a string into ints for day, month, year.
String to be entered follows this convention DDMMYYYY - this will be checked so we can presume it's suitable.

I have it working using tempary variables, but is there a way to do it in one call?

Person getPerson() {
  Person person;
  string dob, temp;
  int date;
  cout << "\nEnter name: ";
  getline(cin, person.name);
  cout << "\nEnter title: ";
  getline(cin, person.title);
  do {
    cout << "\nEnter DOB (DDMMYYYY): ";
    cin >> dob;
    if (atoi(dob.c_str())) break;
  } while (!atoi(dob.c_str()));

  temp = dob.substr(0,2);
  cout << temp; // Sanity check
  person.dob.d = atoi(temp.c_str());
  //person.dob.m = atoi(dob.substr(2,3)); Doesn't work : cannot convert parameter 1 from     'std::basic_string<_Elem,_Traits,_Ax>::_Myt' to 'const char *'
  //person.dob.y = atoi(dob.substr(4,7));
  return person;
}
atoi(dob.c_str())

That's one way to do it. I would do it like this:

istringstream convert(dob);
int intDob =0;
convert >> intDob

And voila: string dob is now saved as an int in intDob!

Edited 6 Years Ago by Nick Evan: n/a

I'm stupid, and can see how to do it,

atoi(dob.substr(2,3).c_str());

sorry everyone ! :-)

That's one way to do it. I would do it like this:

istringstream convert(dob);
int intDob =0;
convert >> intDob

And voila: string dob is now saved as an int in intDob!

I know I marked this as solved, but if I used the istringstream method, how would I then split the integer into individual ints for d, m & y?

This question has already been answered. Start a new discussion instead.