你好,我写了一个后缀计算器使用向量(这是必需的),并遇到了麻烦。当我在一行中输入两个操作数时,它不会给出正确的答案。例如,"5 4 + 3 10 * +"给出的答案是"36",而它应该给出39。我明白为什么它不起作用,我只是想不出一个方法来处理这种情况。有人能帮我一下吗?代码:
#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;
}
休息一段时间后,我找到了解决问题的方法。在这里张贴以防将来有人有同样的问题。下面的代码块现在位于一系列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();
}