Reputation: 4651
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 like this:
int last_space = text_string.find_last_of(' ');
int day = int(text_string.substr(last_space + 1, 2));
But I got invalid cast from type ‘std::basic_string’ to type ‘int’
. When I extract the "John Doe" part in another string variable, all works fine. What's wrong?
I am trying to compile it with g++ -Wall -Werror.
Upvotes: 5
Views: 20108
Reputation: 264331
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).
Upvotes: 3
Reputation: 10162
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.
Upvotes: 0
Reputation: 5393
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.
Upvotes: 5
Reputation: 25551
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/
Upvotes: 0