I have the following data in a C ++ line
John Doe 01.01.1970
I need to extract the date and time from it into int variables. I tried this as follows:
int last_space = text_string.find_last_of(' '); int day = int(text_string.substr(last_space + 1, 2));
But I got it invalid cast from type ‘std::basic_string’ to type ‘int’. When I extract the "John Doe" part in another string variable, everything works fine. What's wrong?
invalid cast from type ‘std::basic_string’ to type ‘int’
I am trying to compile it with g ++ -Wall -Werror.
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 one (white) space. When used with an integer variable, an integer will be read from the stream (discarding any outgoing (white) space).
You need to use
std::stringstream ss; ss << stringVar; ss >> intVar;
or
intVar = boost::lexical_cast<int>(stringVar);.
intVar = boost::lexical_cast<int>(stringVar);
boost.
Boost Data/Time.
, atoi , .
atoi
" C, , int."
http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/
( ), , -
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 );
, / , , (.. , "John M. Doe" ). .
, .
Source: https://habr.com/ru/post/1784959/More articles:In Rails 3, I use the jQuery Tokenize plugin, but the form submits a value, not an identifier - jqueryStructure of the IDENTITY_INSERT object - c #Where did the new line appear in Python? - pythonNested inheritance in C ++ - c ++Confusion - реализованный интерфейс требует кастинга? - collectionsFind the best match from the regex capture group - regexTool for defining Java annotations in various Java APIs - java8 queen issues - actionscript-3"zero" reserved tag number in cocoa? - iphoneHow do I decide if an email was sent, sent, or sent? - c #All Articles