C++字符串转数字

背景

记录一下C++11字符串转数字、数字转字符串

C风格

字符串转数字

头文件:

1
#include <stdlib.h>

函数声明:

1
2
3
4
int atoi(const char *nptr);
long atol(const char *nptr);
long long atoll(const char *nptr);
double atof(const char *nptr);

来实现。

数字转字符串

使用sprintf来实现。
示例:

1
2
3
4
```

## C++风格
两种转换都在头文件

#include

1
2
3
4
命令空间为`std`。

### 字符串转数字
系列函数:

std::stoi,std::stol,std::stoul,std::stoll,std::stoull,std::stof,std::stod,std::stold。

1
2

以stoi为例,示例代码如下:

// stoi example

#include // std::cout

#include // std::string, std::stoi

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; // alias of size_t

int i_dec = std::stoi (str_dec,&sz); // 十进制,注意,sz是转换数字的长度(如2001是4位,sz就是4)
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;
}

1
结果:

2001, A Space Odyssey: 2001 and [, A Space Odyssey]
40c3: 16579
-10010110001: -1201
0x7f: 127

1
2
3
4

### 数字转字符串

函数声明:

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);
`
即转换成字符串,统一使用std::to_string即可。宽字符版本使用std::to_wstring。

具体参考:。