string转化为int

来源:互联网 发布:域名注册检测工具 编辑:程序博客网 时间:2024/05/17 15:06

方法一:

std::string str = "123";
int n =atoi(str.c_str());


 intx=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;    }


0 0
原创粉丝点击