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   玫瑰窃贼  阅读(62)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示