c++后缀计算器不能处理一行中的两个操作数
C++ Postfix Calculator not working with 2 operands in a row
你好,我写了一个后缀计算器使用向量(这是必需的),并遇到了麻烦。当我在一行中输入两个操作数时,它不会给出正确的答案。例如,"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();
}
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 两个字符串在 c++ 中不相等
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 两个文件使用彼此的功能-如何解决
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 停止cmake target_link_libraries将插件中静态库的两个对象文件链接到静态库本身
- 将fold表达式与std::一起用于两个元组
- 是否允许三元运算符在C++中计算两个操作数?
- 将具有相反操作数的两个函数重构为一个
- 如何使用 Boost Spirit x3 编写具有两个后操作数语法的二进制运算符?
- 运算符== 的两个操作数的隐式转换
- 三元运算符将类扩展宏应用于这两个操作数
- 计算具有两个以上操作数的后缀表达式时出现问题
- c++后缀计算器不能处理一行中的两个操作数