由后缀表达式题目: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)

               

posted @ 2020-06-20 16:20  Xxaj5  阅读(236)  评论(0编辑  收藏  举报