您好我已经使用向量(这是必需的)编写了一个后缀计算器并且遇到了麻烦。当我连续输入两个操作数时,它不会给出正确的答案。例如,“5 4 + 3 10 * +”在应该给出 39 时给出了答案“36”。我明白为什么它不起作用我只是想不出一种方法来处理这种情况。有人可以帮帮我吗?代码:
#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;
}