问题描述
- c++ 堆栈四则运算括号操作程序查错的问题
-
这个程序可以输入例如((80+50)*3) 但是为什么会停止工作?这是书上的例程啊...
#include
#include
#include
#include
#include
using namespace std;
double read_and_evaluate(istream& ins);
void evaluate_stack_tops(stack& numbers, stack& operations);int main()
{
double answer;
cout<<"TYPE expression"<<endl;
answer = read_and_evaluate(cin);
cout << "that evaluates to" << answer << endl;
system("pause");
}double read_and_evaluate(istream& ins)
{const char DECIMAL = '.';
const char RIGHT_PARENTHESIS = ')';
stack numbers;
stack operations;
double number;
char symbol;while(ins && ins.peek()!='n')
{
if(isdigit(ins.peek()) || (ins.peek() == DECIMAL))
{
ins >> number;
numbers.push(number);
}
else if(ins.peek() == RIGHT_PARENTHESIS)
{
ins.ignore();
evaluate_stack_tops(numbers, operations);
}
else
ins.ignore();}
return numbers.top();
}void evaluate_stack_tops(stack& numbers, stack& operations)
{
double operand1,operand2;operand2=numbers.top();
numbers.pop();
operand1=numbers.top();
numbers.pop();switch(operations.top())
{
case '+': numbers.push(operand1+operand2);
break;
case '-': numbers.push(operand1-operand2);
break;
case '*': numbers.push(operand1 * operand2);
break;
case '/': numbers.push(operand1/operand2);
break;
}
operations.pop();}
解决方案
要么是堆栈为空了,要么是指针没有处理正确。具体原因调试下。