使用C标准库函数
具体做法是先将string转换为char*字符串,再通过相应的类型转换函数转换为想要的数值类型。需要包含标准库函数<stdlib.h>
。
(1)string转换为int32_t
1
2
3
4
5
|
string love= "77" ;
int ilove= atoi (love.c_str());
//或者16位平台转换为long int
int ilove= strtol (love.c_str(),NULL,10);
|
(2)string转换为uint32_t
1
2
3
4
5
6
7
8
9
|
//str:待转换字符串
//endptr:指向str中数字后第一个非数字字符
//base:转换基数(进制),范围从2至36
unsigned long int strtoul ( const char * str, char ** endptr, int base);
#示例
string love= "77" ;
unsigned long ul;
ul = strtoul (love.c_str(), NULL, 10);
|
(3)string转换为uint64_t
1
2
|
string love= "77" ;
long long llLove=atoll(love.c_str());
|
(4)string转换为uint64_t
1
2
3
4
5
6
|
unsigned long long int strtoull ( const char * str, char ** endptr, int base);
#示例
string love= "77" ;
unsigned long long ull;
ull = strtoull (love.c_str(), NULL, 0);
|
(5)string转换为float或double
1
2
3
|
string love= "77.77" ;
float fLove= atof (love.c_str());
double dLove= atof (love.c_str());
|
(6)string转换为long double
1
|
long double strtold ( const char * str, char ** endptr);
|