[英]How do I properly test whether my postfix expression is valid?
I was given an assignment to write a program that evaluates a postfix expression using the stack. 我被分配编写一个程序,该程序使用堆栈评估后缀表达式。
I wrote the program and it seems to be working for the most part, however it is having issues determining whether the expression is valid. 我编写了该程序,它似乎在大多数情况下都有效,但是它在确定表达式是否有效方面存在问题。
Here are the basic steps that I've done: 以下是我已完成的基本步骤:
So the above works well if the stack is empty already, but if there are more operands on the stack the result simply prints out. 因此,如果堆栈已经为空,则上面的方法效果很好,但是如果堆栈上有更多的操作数,则结果只会打印出来。 This is obviously incorrect because it should be an invalid expression if there are multiple operands still on the stack.
这显然是不正确的,因为如果堆栈上还有多个操作数,则它应该是无效的表达式。
I was thinking I should do a while(!stack.empty()) result = stack.top, stack.pop()
however, this would still have the same issue. 我在想我应该做
while(!stack.empty()) result = stack.top, stack.pop()
但是,这仍然会有同样的问题。
Can someone tell me how I should be testing it properly? 有人可以告诉我如何正确测试吗?
Code: 码:
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 (don't worry, it'll be renamed) function: 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;
}
To validate your expression, you need to test multiple conditions. 要验证您的表达,您需要测试多个条件。
stack.empty()
while popping the arguments to any operator. stack.empty()
。 Stack
doesn't have a method for returning the current stack depth): Stack
没有返回当前堆栈深度的方法):
That should do it. 那应该做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.