'Simple expression calculator in C - stacks' application
Write a program that solves arithmetic expressions, passed as a string, printing its value. Use two stacks, one for operands and one for operators. Consider only + and * operators. Also consider 1-digit operands. Consider operator precedence in solving the expression.
My code is not working, but I cannot see the problem, even though I am looking for it for days. I really appreciate some help!
# include<stdio.h>
# include<stdlib.h>
# include<string.h>
# define MAX 40
int *p1, *p2; // pointers rows operands, operators
int *to1, *to2; // tops rows operands, operators
int *bo1, *bo2; // bases rows operands, operators
void push1(int i), push2(char j); //operating, operator - stack
int pop1(void), pop2(void); //operand, operator - unstack
void push1 (int i)
{
if (p1>bo1)
{
printf("Stack of operands full \n");
}
*p1=i;
p1++;
}
void push2 (char j)
{
if (p2>bo2)
{
printf("Operator stack full \n");
}
*p2=j;
p2++;
}
int pop1()
{
p1--;
if (p1<to1)
{
printf("Empty operand stack \n");
return 0;
}
return *p1;
}
int pop2()
{
p2--;
if (p2<to2)
{
printf("Empty operator stack \n");
return 0;
}
return *p2;
}
void main()
{
int a,b, c, result, i, st;
char o, s[MAX];
p1= malloc(MAX*sizeof(int)); //allocate memory stack 1
p2= malloc(MAX*sizeof(char)); //allocate memory stack 2
to1=p1;
to2=p2;
bo1=p1+MAX-1;
bo2=p2+MAX-1;
printf("Enter the expression\n");
gets(s);
st=strlen(s);
push1(s[0]); //put the first digit
for (i=0; i<(st-1)/2+1; i++)
{push1(s[2*(i+1)]); //stack the next digit
push2(s[2*i+1]); //stack the next operator
if (s[2*i+1]=='*') //if it's multiplication...
{
a=pop1(); // get the last two digits
b=pop1();
o=pop2(); //delete the operator
push1(a*b); // replace with product
}
}
while(p1>to1)
{
a=pop1();
b=pop1();
c=a+b;
push1(c);
}
result=pop1();
printf("Result=%d", result);
}
Solution 1:[1]
walking down the input string should be simple
for(int i = 0; i < st; i++){
char next = s[i];
....
}
why all that complicated 2* , -1, /2+1....?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pm100 |
