C++11 的 stoi()
上一篇介绍了 "int to string" 想了想再把 "string to int" 的补上吧,这一篇就介绍一下 string 中的 stod() & stof() & stoi() & stol() & stold() & stoll() & stoul() & stoull() 方法
如有侵权,请联系删除,如有错误,欢迎大家指正,谢谢
声明
// include <string>
double stod(const string& _Str, size_t *_Idx = nullptr);
float stof(const string& _Str, size_t *_Idx = nullptr);
int stoi(const string& _Str, size_t *_Idx = nullptr, int _Base = 10);
long stol(const string& _Str, size_t *_Idx = nullptr, int _Base = 10);
long double stold(const string& _Str, size_t *_Idx = nullptr);
unsigned long stoul(const string& _Str, size_t *_Idx = nullptr, int _Base = 10);
long long stoll(const string& _Str, size_t *_Idx = nullptr, int _Base = 10);
unsigned long long stoull(const string& _Str, size_t *_Idx = nullptr, int _Base = 10);
能看出来,"string to" 和 "to string" 基本是对应的,转来转去
源码
- string to int
// include <string>
// 这里主要介绍一下string to int 其他方法与这个类似,可到头文件 <string> 中查看
// _Str 转换的字符串
// _Idx 转换的长度(位数)
// _Base 进制
inline int stoi(const string& _Str, size_t *_Idx = nullptr,
int _Base = 10)
{ // convert string to int
int& _Errno_ref = errno; // Nonzero cost, pay it once
const char *_Ptr = _Str.c_str(); // 获取字符串的首地址
char *_Eptr;
_Errno_ref = 0;
// 这是 C 的标准库函数
// _Ptr 要转换字符串的起始地址
// _Eptr 已转换完的字符的下一个地址
// _Base 进制
// stod() & stof() & stol() & stold() & stoll() & stoul() & stoull() 的转换此处可能有差别
const long _Ans = _CSTD strtol(_Ptr, &_Eptr, _Base);
if (_Ptr == _Eptr) // 起始地址和转换完成的下一个地址相等,说明此字符串不能被转换为 int ,是无效参数
_Xinvalid_argument("invalid stoi argument");
if (_Errno_ref == ERANGE || _Ans < INT_MIN || INT_MAX < _Ans) // 越界报错
_Xout_of_range("stoi argument out of range");
if (_Idx != nullptr)
*_Idx = (size_t)(_Eptr - _Ptr); // 计算已转换完成的字符串的长度
return ((int)_Ans);
- string to float
// include <string>
// 与 string to int 的区别在于调用的 C 标准库函数不同
inline float stof(const string& _Str, size_t *_Idx = nullptr)
{ // convert string to float
int& _Errno_ref = errno; // Nonzero cost, pay it once
const char *_Ptr = _Str.c_str();
char *_Eptr;
_Errno_ref = 0;
const float _Ans = _CSTD strtof(_Ptr, &_Eptr);
if (_Ptr == _Eptr)
_Xinvalid_argument("invalid stof argument");
if (_Errno_ref == ERANGE)