I have this code that evaluates post fix expressions and initially, the code does not have user input but has the expression already defined in the main function like this:
int main()
{
char exp[] = "100 200 + 2 / 5 * 7 +";
printf ("%d", evaluation(exp));
return 0;
}
and it will display the answer
However, when I change the code to
int main()
{
char exp[100];
printf("Enter an expression:");
scanf("%s", exp);
printf ("%d", evaluation(exp));
return 0;
}
it doesn't work and it will give me a random number every time I run it
I really don't understand why this is happening. How do I let the function evaluate user input?
Would greatly appreciate some help. Thank you.
Here is the full code:
/*---------------POSTFIX EVALUATION-----------------------------*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
struct posteval
{
int head1;
unsigned size;
int* expression;
};
struct posteval* newstack(int size)
{
struct posteval* posteval2=(struct posteval*)malloc(sizeof(struct posteval));
if(!posteval2)
{
return 0;
}
posteval2->expression=(int*)malloc(posteval2->size * sizeof(int));
posteval2->head1= -1;
posteval2->size = size;
if(!posteval2->expression)
{
return 0;
}
return posteval2;
};
// a function to push into the stack for postfix evaluation
void postpush(struct posteval* posteval2, int x)
{
posteval2->expression[++posteval2->head1] = x ;
}
// a function to pop into the stack for postfix evaluation
int postpop(struct posteval* posteval2)
{
if(!nothing(posteval2))
{
return posteval2->expression[posteval2->head1--];
}
return 'E';
}
//a function that checks if the stack has nothing in it
int nothing(struct posteval* posteval2)
{
return posteval2->head1 == -1;
}
//function that evaluates the postfix expressions
int evaluation(char* exp)
{
int i;
int operand;
int explength=strlen(exp);
int num1, num2;
struct posteval* posteval2=newstack(explength);
if (!posteval2)
{
return -1;
}
for(i=0; exp[i]; ++i)
{
if (exp[i]==' ')
{
continue;
}
else if (isdigit(exp[i]))
{
operand=0;
while(isdigit(exp[i]))
{
operand= operand*10 + (int)(exp[i]-'0');
i++;
}
i--;
postpush(posteval2, operand);
}
else {
num1 = postpop(posteval2);
num2 = postpop(posteval2);
if(exp[i]=='/')
{
postpush(posteval2, num2/num1);
}
else if(exp[i]=='+')
{
postpush(posteval2, num2 + num1);
}
else if (exp[i]=='*')
{
postpush(posteval2, num2 * num1);
}
else if (exp[i]=='-')
{
postpush(posteval2, num2 - num1);
}
}
}
return postpop(posteval2);
}
int main()
{
char exp[100];
printf("Enter an expression:");
scanf("%c", exp);
printf ("%d", evaluation(exp));
return 0;
}
}