atoi、stoi和strtol的使用

1、atoi

    将string字符串转换为int类型,只能转换为十进制;atoi函数不会对string字符串进行范围检查[-2147483648,2147483647],超过这个界限,不会报错,只会进行相应的转换,遇到非法字符会停止,不会报错;头文件为cstdlib

#include<iostream>
#include<cstdlib>
#include<string>
using namespace std;
void atoiInt1(){
	string s="111111";
	cout<<atoi(s.c_str())<<endl;
}
void atoiInt2(){
	string s="111nnn1111";
	cout<<atoi(s.c_str())<<endl;
}
void atoiInt3(){
	string s="2147483648";
	cout<<atoi(s.c_str())<<endl;
}
int main(){
	atoiInt1();
	atoiInt2();
	atoiInt3();
	return 0;
} 

输出:

111111
111
-2147483648

2、stoi

        将string字符串转换为int类型,只能转换为十进制;atoi函数会对字符串进行检查,如果超过范围,会报错,遇到非法字符同样会停下来,不会报错;头文件为string

#include<iostream>
#include<cstdlib>
#include<string>
using namespace std;
int stoiInt1(){
	string s="111111";
	cout<<stoi(s.c_str())<<endl;
}
int stoiInt2(){
	string s="111nnn1111";
	cout<<stoi(s.c_str())<<endl;
}
int stoiInt3(){
	string s="2147483648";
	cout<<stoi(s.c_str())<<endl;
}
int main(){
	stoiInt1();
	stoiInt2();
	stoiInt3();
	return 0;
} 

输出:

111111
111
terminate called after throwing an instance of 'std::out_of_range'

3、strtol

        同样是将string字符串转换为int类型,但这个函数可以自定义转换的string字符串的类型(第三个参数可定义string字符串的类型),strtol超过int范围,不会报错,只会输出最大或者最小值[-2147483648,2147483647],遇到非法字符,则同样停止,不会报错;

#include<iostream>
#include<cstdlib>
#include<string>
using namespace std;
int strtolInt1(){
	string s="111111";
	cout<<strtol(s.c_str(),nullptr,2)<<endl;
}
int strtolInt2(){
	string s="111nnn1111";
	cout<<strtol(s.c_str(),nullptr,10)<<endl;
}
int strtolInt3(){
	string s="21474836482";
	cout<<strtol(s.c_str(),nullptr,10)<<endl;
}
int strtolInt4(){
	string s="-21474836482";
	cout<<strtol(s.c_str(),nullptr,10)<<endl;
}
int main(){
	strtolInt1();
	strtolInt2();
	strtolInt3();
	strtolInt4();
	return 0;
}

输出:

63
111
2147483647
-2147483648


版权声明:本文为godop原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。