字符串转数字
C
<stdlib.h> in C <cstdlib> in C++
C有两个转换函数:
atoi strtol 这两个函数都不会出异常 只会执行到出错位置后返回当前结果 默认结果为0
atoi
int atoi (const char * str);
只能转换10进制的数字字符串为数字
#include <iostream>
int main(){
printf("%d %d %d\n",atoi("1000"),atoi("a1000"),atoi("100a0"));
return 0;
}
结果
1000 0 100
strtol
long int strtol (const char* str, char** endptr, int base);
| 参数 |
---|
str | 数字字符串 | endptr | 指向数字解析完后的地址(下一位)可为NULL | base | 进制[2,36] |
#include <iostream>
int main(){
char *end;
const char*s = "0x1000";
const char*sp="10a3";
printf("%d ",strtol(s,&end,16));
printf("[end]:%d\n",end-s);
printf("%d ",strtol(sp,&end,10));
printf("[end]:%d\n",end-sp);
return 0;
}
输出
4096 [end]:6
10 [end]:2
cpp stoi
<string>
int stoi (const string& str, size_t* idx = 0, int base = 10);
int stoi (const wstring& str, size_t* idx = 0, int base = 10);
idx 参数与strtol 的 endptr 参数作用相同 都是指向数字解析完的下一位 可为nullptr
如果base为0 则进制由字符串格式决定
#include <iostream>
#include <string>
int main(){
std::string str_dec = "2001, A Space Odyssey";
std::string str_hex = "40c3";
std::string str_bin = "-10010110001";
std::string str_auto = "0x7f";
std::string::size_type sz;
int i_dec = std::stoi (str_dec,&sz);
int i_hex = std::stoi (str_hex,nullptr,16);
int i_bin = std::stoi (str_bin,nullptr,2);
int i_auto = std::stoi (str_auto,nullptr,0);
std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";
std::cout << str_hex << ": " << i_hex << '\n';
std::cout << str_bin << ": " << i_bin << '\n';
std::cout << str_auto << ": " << i_auto << '\n';
return 0;
}
结果为
2001, A Space Odyssey: 2001 and [, A Space Odyssey]
40c3: 16579
-10010110001: -1201
0x7f: 127
参考
|