我正在研究一个后缀计算器,我非常接近完成,但我很难理解为什么我的计算器只评估第一个输入。例如,如果我输入:“1 2 3 ++”,它只弹出第一个数字并显示“1”作为答案。我觉得这个问题源于主循环,其中输入和传递给堆栈的数字没有被正确推送。任何建议/提示表示赞赏!谢谢!
class Dstack
{
public:
Dstack();
~Dstack();
void push(double value);
bool pop(double &value);
int size();
bool empty();
int top();
private:
class Node
{
public:
Node(double value, Node *next)
{m_value = value; m_next = next;}
double m_value;
Node *m_next;
};
Node *m_head;
};
Dstack::Dstack()
{
m_head = NULL;
}
Dstack::~Dstack()
{
Node *ptr = m_head;
while (ptr != NULL)
{
Node *temp;
temp = ptr;
ptr = ptr->m_next;
delete temp;
}
}
void Dstack::push(double value)
{
m_head = new Node(value, m_head);
}
bool Dstack::pop(double &value)
{
//Node *ptr = m_head;
if(m_head == NULL)
{
return false;
}
else
{
Node *temp = m_head;
value = m_head->m_value;
m_head = m_head->m_next;
delete temp;
return true;
}
}
int Dstack::size()
{
int num_elements = 0;
Node *ptr = m_head;
while(ptr != NULL)
{
num_elements++;
ptr = ptr->m_next;
}
return num_elements;
}
bool Dstack::empty()
{
if(m_head == NULL)
return true;
else
return false;
}
//main
void error()
{
cerr << "Illegal" << endl;
exit(1);
}
int main()
{
double lVal, rVal, answer;
Dstack stack;
double num;
while((cin.peek()) != -1)
{
if(cin.peek() >= 'a' && cin.peek() <= 'z')
{
error();
}
if(isspace(cin.peek()))
{
cin.ignore();
break;
}
if(isdigit(cin.peek()) || cin.peek() == '.')
{
cin >> num;
if(cin.good())
{
stack.push(num);
}
}
else if(cin.peek() == '+')
{
rVal = stack.pop(num);
lVal = stack.pop(num);
answer = rVal + lVal;
stack.push(answer);
break;
}
else if(cin.peek() == '-')
{
rVal = stack.pop(num);
lVal = stack.pop(num);
answer = rVal - lVal;
stack.push(answer);
break;
}
else if(cin.peek() == '*')
{
rVal = stack.pop(num);
lVal = stack.pop(num);
answer = rVal * lVal;
stack.push(answer);
break;
}
else if(cin.peek() == '/')
{
rVal = stack.pop(num);
lVal = stack.pop(num);
answer = rVal / lVal;
stack.push(answer);
break;
}
else if(cin.peek() == '^')
{
rVal = stack.pop(num);
lVal = stack.pop(num);
answer = pow(rVal, lVal);
stack.push(answer);
break;
}
stack.pop(answer);
}
cout << "\nAnswer: " << answer << endl;
return 0;
}