将c ++字符串转换为int

ska*_*zhy 3 c++ string

我在c ++字符串中有以下数据

John Doe 01.01.1970
Run Code Online (Sandbox Code Playgroud)

我需要从中提取日期和时间到int变量.我试过这样的:

int last_space = text_string.find_last_of(' ');
int day = int(text_string.substr(last_space + 1, 2));
Run Code Online (Sandbox Code Playgroud)

但是我得到了invalid cast from type ‘std::basic_string’ to type ‘int’.当我在另一个字符串变量中提取"John Doe"部分时,一切正常.怎么了?

我试图用g ++ -Wall -Werror编译它.

Axe*_*ing 5

你需要使用

std::stringstream ss; 
ss << stringVar;
ss >> intVar;
Run Code Online (Sandbox Code Playgroud)

要么

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

后者是boost库中的便捷包装器.