背景
记录一下C++11字符串转数字、数字转字符串
C风格
字符串转数字
头文件:
1 | #include <stdlib.h> |
函数声明:
1 | int atoi(const char *nptr); |
来实现。
数字转字符串
使用sprintf来实现。
示例:
1 | ``` |
#include
1 | 命令空间为`std`。 |
std::stoi,std::stol,std::stoul,std::stoll,std::stoull,std::stof,std::stod,std::stold。
1 |
|
// stoi example
#include
#include
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 |
|
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。