2016-09-10 26 views
0

你好我已經寫了一個使用向量(這是必需的)後綴計算器,並遇到了麻煩。當我連續輸入兩個操作數時,它不會給出正確的答案。例如,「5 4 + 3 10 * +」在給出39時給出了答案「36」。我明白爲什麼它不起作用,我只是想不到在處理這種情況下做到這一點的方法。有人能幫我一把嗎? 代碼:C++後綴計算器不能連續使用2個操作數

#include <iostream> 
#include <sstream> 
#include <string> 
#include <vector> 
using namespace std; 

//splits the string into different parts seperated by space and stores in tokens 
void SplitString(string s, char delim, vector<string> &tokens) 
{ 
stringstream ss; 
ss.str(s); 
string item; 
while(getline(ss, item, delim)) 
{ 
    tokens.push_back(item); 
} 
} 

//preforms the operation denoted by the operand 
void operation(string operand, vector<int> &eqVec) 
{ 
int temp1 = eqVec.at(0); 
int temp2 = eqVec.at(1); 

if(operand == "+") 
{ 
    eqVec.push_back(temp1 + temp2); 

} 
else if(operand == "-") 
{ 
    eqVec.push_back(temp1 - temp2); 
} 
else if(operand == "*") 
{ 
    eqVec.push_back(temp1 * temp2); 
} 
else if(operand == "/") 
{ 
    eqVec.push_back(temp1/temp2); 
} 

} 

int main() 
{ 
const char DELIM = ' '; 
int total; 
string eq; 

vector <int> eqVec; 
vector<string> tokens; 


cout<<"Welcome to the postfix calculator! " << endl; 
cout<<"Please enter your equation: "; 

//gets the input and splits into tokens 
getline(cin, eq); 
SplitString(eq, DELIM, tokens); 

//cycles through tokens 
for(int i = 0; i < tokens.size(); ++i) 
{ 

    //calls operation when an operand is encountered 
    if(tokens.at(i) == "+" || tokens.at(i) == "-" || tokens.at(i) == "*" || tokens.at(i) == "/") 
    { 
     operation(tokens.at(i), eqVec); 
    } 

    //otherwise, stores the number into next slot of eqVec 
    else 
    { 

     //turns tokens into an int to put in eqVec 
     int temp = stoi(tokens.at(i)); 
     eqVec.push_back(temp); 
    } 

} 

//prints out only remaining variable in eqVec, the total 
cout<<"The answer is: " << eqVec.at(0) << endl; 






return 0; 
} 
+1

*我只是想不出一種方法來處理它的情況* - 您應該先編寫一個計劃來處理這些情況,然後再編寫任何代碼。結果發生的事情是,你已經將自己編碼爲「需要徹底改寫的角落」。 – PaulMcKenzie

回答

0

休息一會學成歸來後,我找到了一種方法來解決它。張貼在這裏以防萬一未來有同樣的問題。下面的代碼塊現在位於if語句序列之前的操作函數的開頭。

int temp1, temp2; 
int size = eqVec.size(); 
if(size > 2) 
{ 
    temp1 = eqVec.at(size - 1); 
    temp2 = eqVec.at(size - 2); 
    eqVec.pop_back(); 
    eqVec.pop_back(); 
} 
else 
{ 
    temp1 = eqVec.at(0); 
    temp2 = eqVec.at(1); 
    eqVec.pop_back(); 
    eqVec.pop_back(); 
}