C++ atoi和stoi

在做算法题的时候,如果char转为int只需要 c - '0’即可得到对应数字。
但是遇到string类型需要转化为数字就可以调用函数 atoi 和 stoi

通常用法

	string a = "3";
	int num1 = atoi(a.c_str());
	string b = "3";
	int num2 = stoi(b);

头文件

include<cstring>

区别:

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

2. stoi()会做范围检查,默认范围是int,超出范围会runtime error;atoi()不会做范围检查,超出上界,输出上界,超出下界,则输出下界

猜你喜欢

转载自blog.csdn.net/qq_42883222/article/details/115036988
今日推荐