[英]How do I filter a tuple of types depending on whether an expression is valid in Boost.Hana?
[英]How do I properly test whether my postfix expression is valid?
我被分配編寫一個程序,該程序使用堆棧評估后綴表達式。
我編寫了該程序,它似乎在大多數情況下都有效,但是它在確定表達式是否有效方面存在問題。
以下是我已完成的基本步驟:
因此,如果堆棧已經為空,則上面的方法效果很好,但是如果堆棧上有更多的操作數,則結果只會打印出來。 這顯然是不正確的,因為如果堆棧上還有多個操作數,則它應該是無效的表達式。
我在想我應該做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;
}
要驗證您的表達,您需要測試多個條件。
stack.empty()
。 Stack
沒有返回當前堆棧深度的方法):
那應該做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.