I am reading the holy C programming book by K&R, and I took on Exercise 5-10. It asked to write a program expr which evaluated a postfix expression, such as
expr 3 4 *
and I made my output look like,
= 12
The program I wrote works just fine, except for one thing: It will not accept the * character. All other characters work, except for that one, and I can't understand why.
Here is my full program:
Code:
#include <stdio.h>
int ati(char *s);
void push(int a);
int pop(void);
main(int ac, char *arg[]){
int status = 0;
while(--ac>0){
int s;
switch(**++arg){
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
push(ati(*arg));
continue;
case '+':
push(pop()+pop());
continue;
case '*': /* <-- trouble maker any other characters work, such as # and x */
push(pop() * pop());
continue;
case '-':
s = pop();
push(pop()-s);
continue;
case '/':
s = pop();
push(pop()/s);
continue;
default:
printf("Unrecognized Figure!\n");
status = 1;
break;
}
}
printf(!status ? " = %d\n" : "",pop());
}
int ati(char *s){ /* Just a simple string to integer converter I wrote, despite the fact there is one already */
int o = 0;
while(*s!='\0'){
o = 10*o + *s++ - '0';
}
return o;
}
int stack[255];
int p=0;
void push(int a){
stack[p++] = a;
}
int pop(void){
return stack[--p];
}
The case '*': is the trouble maker. I have replaced it with an x, and then it works fine. Does anyone know why the asterisk produces weird results?
(In case it matters, I have Windows Vista)