所以,我有以下(kludgy!)代码用于后缀表达式转换器和计算器的中缀(正如我在上一篇文章中提到的:简单的数值表达式求解器,感谢大家!):
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main()
{
stack<char> operators;
stack<char> output;
stack<char> temp;
stack<char> answer;
string command;
cout << "=>";
cin >> command;
// "Shunting Yard" algorithm
// source: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
for(int i=0; i<command.size(); i++)
{
switch(command[i])
{
case '*': case '+': case '-': case '/': case'(':
operators.push(command[i]);
break;
case ')':
while(operators.top() != '(')
{
output.push(operators.top());
operators.pop();
}
operators.pop();
break;
default:
output.push(command[i]);
break;
}
}
while(!operators.empty())
{
output.push(operators.top());
operators.pop();
}
while(!output.empty())
{
temp.push(output.top());
output.pop();
}
while(!temp.empty())
{
if(temp.top() == '+')
{
int a = atoi(&answer.top());
cout << "A=" << a << endl;
answer.pop();
int b = atoi(&answer.top());
cout << "B=" << b << endl;
answer.pop();
answer.push(b+a);
} else {
answer.push(temp.top());
}
temp.pop();
}
cout << answer.top() << endl;
system("pause");
return 0;
}
无论如何,问题是:如果我输入,例如,3+4,结果是“&”,而正确的结果是“7”。那么,我的代码有什么问题?