由后缀表达式题目:stoi atoi 函数新发现
洛谷上的题:有些·表示一个操作结束~假装没看到
1 #include<iostream> 2 #include<stack> 3 #include<string> 4 #include<cstring> 5 #include<algorithm> 6 using namespace std; 7 8 int main() 9 { 10 string s; 11 stack<int> st; 12 cin >> s; 13 string tmp = ""; 14 for(int i = 0; i < s.size(); i++) 15 { 16 if(s[i] == '+') 17 { 18 int a = st.top(); 19 st.pop(); 20 int b = st.top(); 21 st.pop(); 22 st.push(a + b); 23 } 24 else if(s[i] == '-') 25 { 26 int a = st.top(); 27 st.pop(); 28 int b = st.top(); 29 st.pop(); 30 st.push(b - a); 31 } 32 else if(s[i] == '/') 33 { 34 int a = st.top(); 35 st.pop(); 36 int b = st.top(); 37 st.pop(); 38 st.push(b / a); 39 } 40 else if(s[i] == '*') 41 { 42 int a = st.top(); 43 st.pop(); 44 int b = st.top(); 45 st.pop(); 46 st.push(a * b); 47 } 48 else 49 { 50 if(s[i] == '.') 51 { 52 if(s[i-1] < '0' && s[i-1] > '9') continue; 53 int c = atoi(tmp.c_str()); 54 st.push(c); 55 tmp = ""; 56 } 57 else tmp += s[i]; 58 } 59 } 60 cout << st.top() << endl; 61 system("pause"); 62 return 0; 63 }
首先整数转为字符串有两种:整数转为string 用to_string()
整数转为普通字符数组用itoa()
今天的重点来了,字符串转整数:将string字符串转化为整数stoi() 如果爆int会报错 有越界检查 不过这个函数在洛谷用不了在leetcode可以用, 所以用了c_str,将c++string转化为普通的字符数组,然后在用atoi将字符串转化为整数,即 int c = atoi(tmp.c_str()); ,还有就是 atoi() 不会有越界检查,超过int上界则数就为int上界,超过下界则数就为下界。
c_str:将C++的string转化为C的字符串数组,c_str()生成一个const char *指针,指向字符串的首地址。
atoi():int atoi(const char *nptr)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端