逆波兰求值

 逆波兰式也就是后缀表达式:

  •  1 + 2 --->  1,2,+
  •  1+(2-3) ---> 1,2,3,-,+
  •  1+(5-4)*2 ---> 1,5,4,-,2,*,+
  •  2+5*(6-4)--->2,5,6,4,-,*,+
  •  5+(4-6/2)*3---> 5,4,6,2,/,-,3 ,*, +

代码如下:

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <queue>
using namespace std;

int main()
{
    string str;
    stack<int> sk;
    int s = 0, l = 0, r = 0;
    cout << "请输入逆波兰公式:" << endl;
    while (cin>>str)
    {
        if (str[0] == '#')
        {
            break;
        }           
        //如果第一个是0-9数字则转换为数字压栈
        else if (isdigit(str[0]))
        {
            sk.push(atoi(str.c_str()));
        }
        else
        {
            l = sk.top();
            sk.pop();
            r = sk.top();
            sk.pop();
            switch (str[0])
            {
            case '+':
                s = r + l;
                break;
            case '-':
                s = r - l;
                break;
            case '*':
                s = r * l;
                break;
            case '/':
                s = r / l;
                break;
            }
            //把计算的结果再次压栈
            sk.push(s);
        }
         
    }
    cout << "结果为:" << s << endl;
    system("pause");
    return 0;
}

扩展小知识----c.str()

const char *c_str();
c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同.
       这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。
注意:一定要使用strcpy()函数 等来操作方法c_str()返回的指针

比如:最好不要这样:
char* c;
string s="1234";
c = s.c_str(); //c最后指向的内容是垃圾,因为s对象被析构,其内容被处理

应该这样用:
char c[20];
string s="1234";
strcpy(c,s.c_str());
这样才不会出错,c_str()返回的是一个临时指针,不能对其进行操作

再举个例子
c_str() 以 char* 形式传回 string 内含字符串
如果一个函数要求char*参数,可以使用c_str()方法:
string s = "Hello World!";
printf("%s", s.c_str()); //输出 "Hello World!"

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章