I have the following data in a c++ string
John Doe 01.01.1970
I need to extract the date and time from it into int variables. I tried it li
As far as I can tell, atoi
does what you need.
"Parses the C string str interpreting its content as an integral number, which is returned as an int value."
http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/
Use streams to decode integers from a string:
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::string x = "John Doe 02.01.1970";
std::string fname;
std::string lname;
int day;
int month;
int year;
char sep;
std::stringstream data(x);
data >> fname >> lname >> day >> sep >> month >> sep >> year;
std::cout << "Day(" << day << ") Month(" << month << ") Year(" << year << ")\n";
}
The operator >> when used with a string variable will read a single (white) space separate word. When used with an integer variable will read an integer from the stream (discarding any proceeding (white) space).
Try the Boost Data/Time library.
Assuming (and that might be a bad assumption) that all the data was formatted similarly, I would do something like this
char name[_MAX_NAME_LENTGH], last[_MAX_NAME_LENGTH];
int month, day, year;
sscanf( text_string, "%s %s %2d.%02d.%04d", first, last, &month, &day, &year );
This does however, have the problem that the first/last names that appear in your input are only one word (i.e. this wouldn't work for things like "John M. Doe"). You would also need to define some appropriate maximum length for the string.
It's hard to be more definitive about this solution unless we know more about the input.
You need to use
std::stringstream ss;
ss << stringVar;
ss >> intVar;
or
intVar = boost::lexical_cast<int>(stringVar);
.
The later is a convenience wrapper from the boost library.