我如何将它转换为它接受括号的位置,目前你唯一可以使用的是 2 + 4 * 7。我无法弄清楚如何忽略括号,所以像 (2 + 3) * 7 这样的东西会读out * + 2 3 7. 有什么帮助谢谢。
#include <iostream>
#include <sstream>
#include <stack>
#include <limits>
#include <string>
using namespace std;
int priority(char a)
{
int temp;
if (a == '*' || a == '/' || a == '%')
temp = 2;
else if (a == '+' || a == '-')
temp = 1;
return temp;
}
//start
int main()
{
//declare a string called "infix"
string infix;
stringstream output;
stack<char> s1, s2;
cout << "Enter an arithmetic expression with no perenthesis: " << endl;
getline(cin, infix);
//this loops through backwards searching for the operators
for(int i = infix.length() - 1; i >= 0; i--)
{
//check the input against +,-,/,*,%
if (infix[i] == '+' || infix[i] == '-' ||
infix[i] == '*' || infix[i] == '/' || infix[i] == '%')
{
while(!s1.empty() && priority(s1.top()) > priority(infix[i]))
{
output << s1.top();
s2.push(s1.top());
s1.pop();
}
s1.push(infix[i]);
}
// I think i need to add an else if to check for parenthesis
// not sure how
else
{
output << infix[i];
s2.push(infix[i]);
}
}
while(!s1.empty())
{
output << s1.top();
s2.push(s1.top());
s1.pop();
}
cout << "\nAnswer: ";
while(!s2.empty())
{
cout << s2.top();
s2.pop();
}
cout <<"\n\nPress enter to exit" << endl;
}