2009-12-09 62 views
2

我想實現前綴中綴在c + +,這就是我到目前爲止。輸入應該是例如這樣的事情:前綴中的堆棧

/7+23 

而且輸出繼電器:

7/(2+3) or (7/(2+3)) 

而是我得到:

(/) 

這是我寫到目前爲止代碼:

void pre_to_in(stack<char> eq) { 
    if(nowe.empty() != true) { 
     char test; 
     test = eq.top(); 
     eq.pop(); 
     if(test == '+' || test == '-' || test == '/' || test == '*') { 
      cout << "("; 
      pre_to_in(eq); 
      cout << test; 
      pre_to_in(eq); 
      cout << ")"; 
     } else { 
      cout << test; 
     } 
    } 
} 


// somewhere in main() 
char arr[30]; 
stack<char> stosik; 
int i = 0; 
cout << "write formula in prefix notation\n"; 
cin >> arr; 

while(i < strlen(arr)) { 
    stosik.push(arr[i]); 
    i++;   
} 
pre_to_in(stc); 
+1

這是功課嗎?如果是這樣,請將其標記爲。 – 2009-12-09 22:39:02

+3

感謝您先嚐試解決問題,然後向我們展示您擁有的所有信息。 *謝謝。* – GManNickG 2009-12-09 22:39:17

+2

你的意思是按價值複製,還是忘記了&,即: pre_to_in(堆棧&eq)? – Mic 2009-12-09 22:41:52

回答

0
cin >> arr; 

只讀取輸入的一個「單詞」,而不是整行。這裏只是獲得第一個斜線字符。

+0

責備我,我增加了額外的空間來澄清輸入和輸出。問題修復。不幸的是,這不是一個解決方案。 – blid 2009-12-09 22:52:27

1
  1. 這是一個堆棧。先入,後出。你需要反向輸入字符串「32 + 7 /」。

  2. 您使用許多堆棧。在每個輸入到pre_to_in()的堆棧中都被複制。使用參考或指針,例如:void pre_to_in(stack<char> &eq);

那就是所有。

P.S.統一名稱(S /諾威/ EQ/G & & S/STC/stosik/G)

+0

Ad.1。參見http://pl.wikipedia.org/wiki/Odwrotna_notacja_polska Ad.2。請參閱http://pl.wikibooks.org/wiki/C%2B%2B/Referencje 這兩個網站在波蘭。 – rysson 2009-12-09 23:18:54

0

不知道,如果你正在尋找這樣的解決方案,反正你提到的輸入它給人的輸出從您發佈

它讀取STD輸入

我已經建立了現在的Visual Studio 2005下令牌 - 終止輸入回車,按Ctrl + Z,輸入

但在其他的編譯器終端可以以另一種方式

工作
#include <algorithm> 
#include <deque> 
#include <iostream> 
#include <string> 

typedef std::deque<std::string> tokens_t; 

void pre_to_in(tokens_t* eq) 
{ 
    if (!eq->empty()) { 
     const std::string token = eq->front(); 
     eq->pop_front(); 
     if ((token == "+") || (token == "-") || (token == "/") || (token == "*")) { 
      std::cout << "("; 
      pre_to_in(eq); 
      std::cout << token; 
      pre_to_in(eq); 
      std::cout << ")"; 
     } else { 
      std::cout << token; 
     } 
    } 
} 


int main() 
{ 
    std::cout << "write formula in prefix notation" << std::endl; 

    tokens_t tokens; 
    std::copy(
     std::istream_iterator<std::string>(std::cin), 
     std::istream_iterator<std::string>(), 
     std::back_inserter(tokens)); 

    pre_to_in(&tokens); 
}