stoi(),atoi() ,to_string

stoi(),atoi() ,to_string 这三个函数都是对字符串处理的函数,前两者是将字符串转化为十进制 int 类型,最后一个是将十进制类型 int、double 等转化为string
头文件都是:#include<cstring>

stoi() 和 atoi()
这两个功能虽然都是将字符串转化为 int 类型,但是还是有区别的,
stoi 的参数是 const string* 类型
atoi 的参数是 const char* 类型

stoi() 会对转化后的数进行检查,判断是否会超出 int 范围,如果超出范围就会报错;
atoi() 不会对转化后的数进行检查,超出上界,输出上界,超出下界,输出下界;

还有一点,如果使用 atoi 对字符串 string 进行转化的话,就需要 c_str() 函数将 const string* 类型 转化为 cons char* 类型

 1 #include<iostream>
 2 #include<cstring>
 3 using namespace std;
 4 
 5 int main() {
 6     string s = "12345";
 7     int num1 = stoi(s);
 8     int num2 = atoi(s.c_str());// 转化为const char* 
 9     cout << num1 << endl << num2 << endl;//12345   12345
10     return 0;
11 }

 参考博客C++中stoi(),atoi() ,to_string()使用技巧_YXXYX的博客-CSDN博客

posted on 2023-08-25 15:03  玫瑰窃贼  阅读(33)  评论(0编辑  收藏  举报