我被赋予了编写程序的任务,该程序使用堆栈来评估后缀表达式。
我编写了程序,它似乎在大多数情况下工作,但它确定表达式是否有效存在问题。
以下是我完成的基本步骤:
因此,如果堆栈已经为空,则上述工作正常,但如果堆栈上有更多操作数,则结果只会打印出来。这显然是不正确的,因为如果堆栈上仍有多个操作数,它应该是一个无效的表达式。
我在想我应该做while(!stack.empty()) result = stack.top, stack.pop()
但是,这仍然会有同样的问题。
有人能告诉我应该如何正确测试吗?
代码:
int main()
{
string expression;
char response;
int result = -1; //result of expression. Initialized to -1
Stack stack;
printMenu();
do {
cout << "Would you like to enter an expression? (y / n)" << endl;
cin >> response;
response = toupper(response);
switch(response)
{
case 'Y':
//needed due to new line
cin.ignore();
doWork(stack, expression, result);
break;
case 'N':
cout << "Exiting program." << endl;
break;
default:
cout << "Invalid response. Try again." << endl;
}
} while(response != 'N');
return EXIT_SUCCESS;
}
doWork(别担心,它会被重命名)功能:
void doWork(Stack stack, string expression, int result)
{
cout << "Enter a PostFix expression: ";
getline(cin, expression);
for(int i = 0; i < expression.size(); i++)
{
if(expression[i] == ' ') {
//do nothing
} else if(isInteger(expression[i])) {
stack.push(convertChar2Int(expression[i]));
} else if(isOperator(expression[i])) {
// pop last 2 ints from stack and do arithmetic on them
int a = stack.top();
stack.pop();
int b = stack.top();
stack.pop();
// push result onto stack
stack.push(calculate(a, b, expression[i]));
} else {
//cerr : enter different expression
cout << expression[i] << " is an invalid character." << endl;
}
}
//the result should be the top of stack
// THIS IS WHERE MY ISSUE IS
if(!stack.empty()) {
result = stack.top();
stack.pop();
} else {
cout << "Invalid expression." << endl;
}
cout << "Result: " << result << endl;
}
答案 0 :(得分:4)
要验证表达式,您需要测试多个条件。
stack.empty()
。Stack
没有返回当前堆栈深度的方法):
应该这样做。