954,219 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

atoi(string.substr(x,x)) Possible?

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;
}
alcoheca
Light Poster
26 posts since Nov 2007
Reputation Points: 10
Solved Threads: 0
 
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!

Nick Evan
Not a Llama
Moderator
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
 

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

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

sorry everyone ! :-)

alcoheca
Light Poster
26 posts since Nov 2007
Reputation Points: 10
Solved Threads: 0
 

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?

alcoheca
Light Poster
26 posts since Nov 2007
Reputation Points: 10
Solved Threads: 0
 

Here's a link to the istringstream class

For your problem I'd probably use get() or ignore().

Nick Evan
Not a Llama
Moderator
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You