How do I read in the following input in my RPN calculator so that it will find the operator no matter what order?
2
2+
4
As of now my scanf only sees the first char in the string and I can only do this:
2
2
+
4
I m also trying to add an option for integer vs floating point mode. (ex. when i is entered, operate in floating point and vice versa.)
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int *p;
int *tos;
int *bos;
void push(int i);
int pop(void);
int main (void)
{
int a, b;
//float c, d;
char s[80];
//char op; //declare string of 80 chars
p = (int *) malloc(MAX*sizeof(int)); //get stack memory
if (!p){
printf("Allocation Failure
");
exit(1);
}
tos = p;
bos = p + MAX-1;
printf("
RPN Calculator
");
printf("Enter i for integer mode
");
printf("Enter f for floating point mode
");
printf("Enter q to quit
");
do {
printf("> ");
// gets(s);
// scanf("%s", s); //read integer
scanf("%s", s);
// switch (*s) {
switch(*s) {
case i :
printf("(Integer Mode)
");
break;
case f :
printf("(Floating Point Mode)
");
break;
case + :
a = pop();
b = pop();
printf("%d
", a+b);
push(a+b);
break;
case - :
a = pop();
b = pop();
printf("%d
", b-a);
push(b-a);
break;
case * :
a = pop();
b = pop();
printf("%d
", a*b);
push(a*b);
break;
case / :
a = pop();
b = pop();
if(a == 0){
printf("Cannot divide by zero
");
break;
}
printf("%d
", b/a);
push(b/a);
break;
case . :
a = pop();
push(a);
printf("Current value on top of stack: %d
", a);
break;
default:
push(atoi(s));
}
} while (*s != q );
return 0;
}
// Put an element on the stack
void push (int i)
{
if (p > bos){
printf("Stack Full
");
return;
}
*p = i;
p++;
}
// Get the element from the top of the stack
int pop (void)
{
p--;
if(p < 0) {
printf("Stack Underflow
");
return 0;
}
return *p;
}