If I were going to write an RPN calculator I would not actually write my own parser for it unless I needed to convert from infix notation.
It would be beneficial to break up the string into pieces before you try to calculate:
Code:
char **
rpn_break(char *eq, char **stack, int *n)
{
int size = 6; // stack size guess.
stack = malloc(size * sizeof(*stack));
if (stack == NULL)
return NULL;
char *token;
int i = 0;
for (token = strtok(eq, "\n\t "); token != NULL; token = strtok(NULL, "\n\t "))
{
if (i == size) {
char *temp;
size *= 2;
temp = realloc(stack, size);
if (temp == NULL)
{
free(stack);
return NULL;
}
stack = temp;
}
stack[i++] = token;
}
*n = i;
return stack;
}
int
main(void) {
int size = 0;
char **stack = NULL;
char eq[BUFSIZ];
puts("enter RPN equation here:");
fgets(eq, sizeof eq, stdin);
stack = rpn_break(eq, stack, &size);
for (int i = 0; i < size; i++) {
printf("stack[%d] = \"%s\"\n", i, stack[i]);
}
free(stack);
stack = NULL;
return 0;
}
We can reasonably expect the result on your example to be
stack[0] = "3"
stack[1] = "2"
stack[2] = "+"
stack[3] = "pi"
stack[4] = "-"
The code that you currently have is exceptionally brittle, because the stack is just a string, so every operand has to fit in a character. This just isn't a reasonable expectation. The constant pi can't be stored as a single character, and neither can multiple digit numbers.
The other thing I want to ask you is how to make the program realise the different types of ispunct and act differently according to that type (+, -, *, and /).
Well, if the tokens are strings, then strcmp(stack[i], foo) would return 0 for any string foo, like "-", "+", etc.
I think push is coded incorrectly, as well. Variable top is initially 0, instead of -1 like you apparently expect in your code, so I would actually write something to the effect of:
Code:
int top = -1;
void push(stack, x)
{
if (top == MAX - 1)
{
status = 0;
}
else
{
stack[++top] = x;
status = 1;
}
}
Now top always points to the first element in the stack instead of something else without wasting any stack space.