#include <iostream>
#include <string>
#include <stack>
#include <sstream>
using namespace std;
stack<int>aStack;
stack<int>operand1;
stack<int>operand2;
stringstream postfix;
stringstream &postfixExp(string ch)
{
for(int i =0; i< ch.length(); i++)
{
if(ch[i] == '1' || ch[i] == '2' || ch[i] == '3' || ch[i] == '4' || ch[i] == '5' || ch[i] == '6' || ch[i] == '7' || ch[i] == '8' || ch[i] == '9' || ch[i] == '0' )
{
aStack.push(ch[i]);
}
else if(ch[i] == '+')
{
operand1.push(aStack.top());
aStack.pop();
operand2.push(aStack.top());
aStack.pop();
int x = operand1.top() - 48;
int y = operand2.top() - 48;
int result = x + y;
aStack.push(result);
}
else if(ch[i] == '*')
{
operand1.push(aStack.top());
aStack.pop();
operand2.push(aStack.top());
aStack.pop();
int x = operand1.top() - 48;
int y = operand2.top() - 48;
int result = x * y;
aStack.push(result);
}
}
postfix << aStack.top();
return postfix;
}
int main()
{
string postfix = "32+2*";
stringstream * result = &postfixExp(postfix);
cout << result-> str() ;
return 0;
}
嗨,有人知道我上面的代码有什么问题吗? 我的程序应该返回后缀表示法的值。我输入“32+2*”作为后缀表示法,它应该返回 10。显然出了问题,它返回 -86 而不是
我想错误来自这个特定的代码
else if(ch[i] == '*')
{
operand1.push(aStack.top());
aStack.pop();
operand2.push(aStack.top());
aStack.pop();
int x = operand1.top() - 48;
int y = operand2.top() - 48;
int result = x * y;
aStack.push(result);
}
从那里,我显示了操作数 2,它显示 -43 而不是 7(源自之前的加法“34+”)
请告诉我哪一部分是错误的,为什么我的操作数 2 的值不是 7。
谢谢
最佳答案
if(ch[i] == '1' || ch[i] == '2' || ch[i] == '3' || ch[i] == '4' || ch[i] == '5' || ch[i] == '6' || ch[i] == '7' || ch[i] == '8' || ch[i] == '9' || ch[i] == '0' )
{
aStack.push(ch[i]);
}
这应该是:
if(ch[i] == '1' || ch[i] == '2' || ch[i] == '3' || ch[i] == '4' || ch[i] == '5' || ch[i] == '6' || ch[i] == '7' || ch[i] == '8' || ch[i] == '9' || ch[i] == '0' )
{
aStack.push(ch[i] - '0');
}
摆脱其他 - 48
,因为它们已损坏。
关于c++ stack stringstream函数返回整数与ASCII,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18972271/