#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而不是C++堆棧stringstream函數返回整數與ASCII
我想這個錯誤來自這個特殊的代碼
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 。
謝謝
你的堆棧應該包含ASCII字符值還是整數值?你的一些代碼假設爲ASCII('aStack.push(ch [i]);'),一些假設爲數字('aStack.push(result);')。所以當然你會得到荒謬的答案。 –
它應該是數字。然而有人建議我用48減去我的ASCII。通過減去這些,它會給出正確的數值0-9 – dodgerblue
你誤解了他們的建議。它們意味着將ASCII值壓入堆棧時,而不是從堆棧中刪除數值。 –