Convert C ++ string to int

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?

I am trying to compile it with g ++ -Wall -Werror.

+3
source share
5 answers

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).

+3
source

You need to use

std::stringstream ss; 
ss << stringVar;
ss >> intVar;

or

intVar = boost::lexical_cast<int>(stringVar);.

boost.

+5
+2

( ), , -

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" ). .

, .

0

Source: https://habr.com/ru/post/1784959/


All Articles