方法一:
std::string str = "123";
int n = atoi(str.c_str());
int
x=
static_cast
<
int
>(
atof
(s.c_str()));
atof函数:
功 能: 把字符串转换成浮点数
用 法: double atof(const char *nptr);
atoi函数:
功 能: 把字符串转换成长整型数
用 法: #include <stdlib.h>
int atoi(const char *nptr);
c_str()函数:
const char *c_str(); c_str()函数返回一个指向正规C字符串的指针常量, 内容与本string串相同. 这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。
方法二:
自己定义一个函数
int str_to_int(string s) {
int n = s.size();
int result = 0;
int sign = 1;
if (s[0] == '-' || s[0] == '+') {
if (s[0] == '-')
sign = -1;
for (int i = 1; i < n; ++i) {
result = result * 10 + s[i] - '0';
}
}
else {
for (int i = 0; i < n; ++i)
result = result * 10 + s[i] - '0';
}
return sign * result;
}