2016-09-10 12 views
0

こんにちは私はベクトルを使ってポストフィックス計算機を作成しました(これは必須です)。 2つのオペランドを連続して入力すると、正しい答えが得られません。例えば、 "5 4 + 3 10 * +"は39に与えるべき答えを "36"とします。なぜ動作していないのか理解していますが、そのケースを処理する方法は考えられません。誰かが私に手を差し伸べることができる? コード:C++ Postfix Calculatorが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(); 
} 
関連する問題