Nov 13, 2011 at 3:21pm UTC
I made a program and I have a problem here.
Problems ::
1. This code accepts 1 digit only if you enter 5 6 + this program shows 11 but it you enter 11 22 + it shows 4. please help me out to change it upto 3 digits.
2. If a user enters 2 operators like 30 40 + * it should display an error "Two operators are not allowed"
3. if user enters 6 2 3 + - 3 8 2 / + * 2 ^ 3 + result 52 should appear.
here is the code.....
// Code
#include <stdio.h>
#include <ctype.h>
#include <iostream>
#include <stdlib.h>
#include <string>
#include <sstream>
#include <fstream>
#include <cstdio>
#include <iomanip>
#include <cstdlib>
#define MAX 50
#define EMPTY -1
struct stack
{
int data[MAX];
int top;
};
void emptystack(struct stack* s)
{
s->top = EMPTY;
}
void push(struct stack* s,int item)
{
if(s->top == (MAX-1))
{
printf("\nSTACK FULL");
}
else
{
++s->top;
s->data[s->top]=item;
}
}
int pop(struct stack* s)
{
int ret=EMPTY;
if(s->top == EMPTY)
printf("\nSTACK EMPTY");
else
{
ret= s->data[s->top];
--s->top;
}
return ret;
}
void display(struct stack s)
{
while(s.top != EMPTY)
{
printf("\n%d",s.data[s.top]);
s.top--;
}
}
int evaluate(char *postfix)
{
char *p;
struct stack stk;
int op1,op2,result;
emptystack(&stk);
p = &postfix[0];
while(*p != '\0')
{
/* removes tabs and spaces */
while(*p == ' ' || *p == '\t')
{
p++;
}
/* if is digit */
if(isdigit(*p))
{
push(&stk,*p - 48);
}
else
{
/* it is an operator */
op1 = pop(&stk);
op2 = pop(&stk);
switch(*p)
{
case '+':
result = op2 + op1;
break;
case '-':
result = op2 - op1;
break;
case '/':
result = op2 / op1;
break;
case '*':
result = op2 * op1;
break;
case '%':
result = op2 % op1;
break;
case '^':
result = op2 ^ op1;
break;
default:
printf("\nInvalid Operator");
return 0;
}
push(&stk,result);
}
p++;
}
result = pop(&stk);
return result;
}
int main()
{
char exp[MAX];
printf("Enter Postfix Exp<b></b>ression : ");
gets(exp);
printf("%s EQUALS %d\n",exp,evaluate(&exp[0]));
gets(exp);
return 0;
}
/* SAMPLE OUTPUT:
Enter Postfix Exp<b></b>ression : 3 5 + 2 /
3 5 + 2 / EQUALS 4
*/
// End Code