如何使用ASCII转换使用字符堆栈来计算后缀表达式 [英] How to evaluate a postfix expression using character stack using ASCII conversions
问题描述
The code is implemented using ADT by including the "stack.h" user defined header file.
The header file has code for stack operation. I am getting wrong outputs for results greater than 9.
What changes should I make in the code to get the correct output.
I have to use a stack with char data and not int data.
#include<iostream>
#include<string.h>
#include "stack.h"
using namespace std;
void posteva(char postfix[])
{
stack s;
int i=0;
while(postfix[i]!='\0')
{
char x=postfix[i];
if(isdigit(x))
{
s.push(x);
}
else
{
int op1=s.pop()-'0';
int op2=s.pop()-'0';
int res;
switch(x)
{
case '+':
res=op1+op2;
break;
case '-':
res=op1-op2;
break;
case '*':
res=op1*op2;
break;
case '/':
res=op1/op2;
break;
case '%':
res=op1%op2;
break;
}
s.push(res+'0');
}
i++;
}
cout<<"\n\nRESULT :"<<s.pop();
}
int main()
{
char postfix[20];
cout<<"\n\nEnter the postfix : ";
cin>>postfix;
posteva(postfix);
}
我尝试过:
例如,对于后缀表达式63 *,我得到结果为B.
What I have tried:
For example, for postfix expression "63*" I am getting result as B.
推荐答案
s.push(res+'0');
这只适用于单个数字的结果。在你的情况下,6 * 3 = 18.字符'0'相当于0x30,或十进制48. 48 + 18 = 66或十六进制0x42,这是ASCII字符'B'的数值。
That will only work for a single digit result. In your case, 6 * 3 = 18. The character '0' is equivalent to 0x30, or decimal 48. 48 + 18 = 66 or hexadecimal 0x42, which is the numeric value of the ASCII character 'B'.
用于后缀表达式63 *我得到结果为B。
for postfix expression "63*" I am getting result as B.
有罪是:
Guilty is:
s.push(res+'0');
因为代码只对单位数值有效。
为了处理超过1位数的数字,你需要在数字之间设置分隔符,通常使用一个空格:
because the code is correct only for single digit values.
In order to handle numbers with more than 1 digit, you need to have separator between numbers, a space is usually used for this:
2 63 3*+
我的建议是在转换为整数后在堆栈上推送值,但是你必须重写代码以处理数字的输入> 9。
My advice is to push values on stack after converting to integers, but you have to rewrite your code to handle entry of number > 9.
你正在推动堆栈上的单个数字/字符。当一个数字大于9时,你将推送多个数字,这些数字必须全部弹出并转换为数字。
这完全取决于输入的格式。假设有类似num1 num2 op的东西,我建议编写推送和弹出数字的函数:
You are pushing single digits / characters on the stack. When a number is greater than 9 you will push multiple digits that must be all popped and converted to a number.
It all depends on how the input is formatted. Assuming something like "num1 num2 op", I suggest to write functions to push and pop numbers:
int pushdigit(const char* input, int pos, stack *s)
{
while (istdigit(input[pos])
{
s->push(input[pos++]);
}
// Push a zero as end of number indicator
s->push(0);
// Return position to next input character skipping space
return (' ' == input[pos]) ? pos + 1 : pos;
}
int popdigit(stack *s)
{
int num = 0;
int mult = 1;
// Assuming the stack provides a function to check if it is empty
while (!s->isempty())
{
char c = s->pop();
if (!isdigit(c))
break;
num += mult * (c - '0');
mult *= 10;
}
return num;
}
这篇关于如何使用ASCII转换使用字符堆栈来计算后缀表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!