天天看点

数字字符串转换为数字:stoi()和atoi()

相同点:

①都是C++的字符处理函数,把数字字符串转换成int输出

②头文件都是#include

不同点:

①atoi()的参数是 const char* ,因此对于一个字符串str我们必须调用 c_str()的方法把这个string转换成 const char类型的,而stoi()的参数是const string&,不需要转化为 const char;

②stoi()会做范围检查,默认范围是在int的范围内的,如果超出范围的话则会runtime error!而atoi()不会做范围检查,如果超出范围的话,超出上界,则输出上界,超出下界,则输出下界;

// 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);      
stoi()函数如果传入的字符串s中含有不是数字的字符,则只会识别到从开头到第一个非法字符之前,如果第一个字符就是非法字符则会报错