#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
string blah("512+4*+3−");
stack<int> astack;
int a=0;
int b=0;
int result=0;
int final=0;
for (string::iterator count=blah.begin(); count != blah.end(); count=count+1)
{
if (isdigit(*count))
{
astack.push(*count);
cout<<" "<<*count<<" ";
}
else
{
a=astack.top();
astack.pop();
b=astack.top();
astack.pop();
if(*count=='+')
{
result = a+ b;
}
else if (*count=='-')
{
result=a-b;
}
else if(*count=='*')
{
result=a*b;
}
astack.push(result);
}
}
final=astack.top();
cout<<final;
}
我的問題是每當我運行它時,代碼似乎會分段錯誤。當我試着運行它與運營商評論它堆棧似乎彈出兩個值,我不知道爲什麼用堆棧和迭代器編寫後綴計算器
護理,告訴我們您的調試器導致錯誤報告的行? – 2014-11-03 02:19:23
如果第一個字符不是數字,會發生什麼情況?它將查詢空堆棧的頂部。放置大量'assert'來檢查這些假設,並且可能會陷入錯誤。 – 2014-11-03 02:20:52
那麼,您發佈的'blah'字符串中的「 - 」符號不是負號。此外,不能重複:http://ideone.com/xqQSmM – PaulMcKenzie 2014-11-03 02:29:36