thank Salem. I have other problem about passing by value of variable "operator" at function "void operation(char operator)". The output is very strange. It cannot display "+", "-" or "*" properly. What's wrong?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DELIM " "
#define MAXWORD 100
#define MAXLEN 10
#define MAX_PS 1000
int postStack[MAX_PS];
int top;
void push(int x)
{
top++;
postStack[top] = x;
}
int pop()
{
if (top >= 0) {
top--;
return postStack[top+1];
}
}
void initStack()
{ top = -1; }
void operation(char operator)
{
int a, b, result;
a = pop();
b = pop();
if (operator == '+')
result = a+b;
else if (operator == '-')
result = a-b;
else if (operator == '*')
result = a*b;
push(result);
printf("%d %c %d = %d\n", a, b, operator, result);
}
int main()
{
char words[MAXWORD][MAXLEN];
char buff[BUFSIZ];
int n, i;
initStack();
n = 0;
if (fgets(buff, sizeof buff, stdin) != NULL) {
char *sep = strtok(buff, DELIM);
while (sep != NULL) {
strcpy(words[n++], sep);
sep = strtok(NULL, DELIM);
}
}
for (i = 0; i < n; i++) {
if ((words[i][0] != '+') && (words[i][0] != '-') && (words[i][0] != '*'))
push(atoi(words[i]));
else operation(words[i][0]);
}
return 0;
}
data input/output
Code:
input:
6 4 * 2 +
output:
4 42 = 0
2 ▒ 43 = 0