逆波蘭求值

 逆波蘭式也就是後綴表達式:

  •  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!"

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