2013-03-29 33 views
0

我該如何將它轉換爲它接受括號的地方,目前唯一可以使用的就是2 + 4 * 7。我無法弄清楚如何忽略括號,所以像(2 + 3)* 7會讀出* + 2 3 7.任何事情都有助於感謝。插入前綴括號

#include <iostream> 
#include <sstream> 
#include <stack> 
#include <limits> 
#include <string> 
using namespace std; 

int priority(char a) 
{ 
    int temp; 

    if (a == '*' || a == '/' || a == '%') 
     temp = 2; 
    else if (a == '+' || a == '-') 
     temp = 1; 
    return temp; 
} 

//start 
int main() 
{ 
    //declare a string called "infix" 
    string infix; 
    stringstream output; 
    stack<char> s1, s2; 

    cout << "Enter an arithmetic expression with no perenthesis: " << endl; 
    getline(cin, infix); 

    //this loops through backwards searching for the operators 
    for(int i = infix.length() - 1; i >= 0; i--) 
    { 
     //check the input against +,-,/,*,% 
     if (infix[i] == '+' || infix[i] == '-' || 
      infix[i] == '*' || infix[i] == '/' || infix[i] == '%') 
     { 
      while(!s1.empty() && priority(s1.top()) > priority(infix[i])) 
      {  
       output << s1.top(); 
       s2.push(s1.top()); 
       s1.pop();   
      } 

      s1.push(infix[i]); 
     } 
     // I think i need to add an else if to check for parenthesis 
     // not sure how 
     else 
     { 
      output << infix[i]; 
      s2.push(infix[i]); 
     } 
    } 

    while(!s1.empty()) 
    { 
     output << s1.top(); 
     s2.push(s1.top()); 
     s1.pop(); 
    } 

    cout << "\nAnswer: "; 

    while(!s2.empty()) 
    { 
     cout << s2.top(); 
     s2.pop(); 
    } 

    cout <<"\n\nPress enter to exit" << endl; 
} 

回答

0

正如您所指出的,您打算將中綴轉換爲前綴表示法。 不幸的是,你的任務不會像只跳過一些括號一樣簡單。

與沒有圓括號的前綴表示法相比,中綴表示法要求他們任意描述任何可能的計算結果。

拿這個爲例:

(1 + 2)/(3 + 4) 

,而這可以很好寫下來作爲

/+ 1 2 + 3 4 

在前綴符號,你不會找到任何方式來表達綴相同的計算沒有任何括號的符號。

而不是試圖順序分析每一個操作之後,將需要一個完整的解析器建立您的字符串的中綴樹的中綴表示法。

否則沒有機會獲得計算權。想想像

(1 + 2 * (3/(4 + 3) * 48 + (81/4)) + 8) - 9 

例如。

與您的問題有關的術語,您可能想要調查通常稱爲表達語法

看看這裏例如:(參見:http://en.wikipedia.org/wiki/Parsing_expression_grammar

+0

逆波蘭式是後綴是不是?這是中綴 – user2206227

+0

@ user2206227的前綴 - 那麼只需按照相反的順序閱讀堆棧,以便從後綴更改爲前綴。 –

+0

你是絕對正確的 - 反向擦亮是完全廢話。儘管如此,反映符號不會改變上述任何陳述。無論如何,我會解決它們。 – mikyra