Originally Posted by
matsp
But that's not the code you've presented in this thread - it reads a string containing postfix operations, so that's where the separators need to be (infix, you can use the operator as a separator, so you don't need to do anything there). If you compare it with a HP calculator, you have to hit enter between two numbers, then hit + to add them. I'm not sure if the "infix to postfix" is part of this same application (but not shown here), or if it's a separate application. Either way, your string that is input to your postfix parser is the part that needs the separation!
--
Mats
ok I have succeded in making my infix code produce postfix delimited by spaces, so 13.5+25 will be 13.5 25 + Can you guide me or someone guide me on how to construct the loop cos I need a loop to read through the string and convert it to double before pushing it. This has been difficult for, please assist me.
Code:
#include<stdio.h>
#include<stdlib.h>
#define MAXCOLS 80
main(){
char instring[MAXCOLS], postring[MAXCOLS];
int position = 0;
float eval();
float result;
printf("%s", "Enter postfix expression: ");
while ((postring[position++] = getchar()) != '\n');
postring[--position] = '\0';
printf("%s%s", "postfix expression is", postring);
getchar();
result=eval(postring);
printf("%s%f\n", "value is", result);
getchar();
}
struct stack{
int top;
float items[MAXCOLS];
};
float eval(expr)
char expr[];
{
int c, position;
float op1, op2, value;
float oper(), pop();
struct stack opndstk;
opndstk.top = -1;
for (position =0; (c=expr[position]) != '\0'; position++)
if(isdigit(c))
/*I guess this is the point I need a loop to convert to double, if I have 44 55 +, I need to read in 44 convert it to double push it, skip the space and read 55, this code below should do the conversion but I don't know how to integrate it.
double val, power,res;
int sign;
sign = (expr[i] == '-') ? -1 : 1;
for (val = 0.0; isdigit(expr[i]); i++)
val = 10.0 * val + (expr[i] - '0');
if (expr[i] == '.')
{
i++;
}
else
{
}
for (power = 1.0; isdigit(expr[i]); i++)
{
val = 10.0 * val + (expr[i] - '0');
power *= 10;
}
res= sign * val / power;
push(&opndstk, res)*/
push (&opndstk, (float)(c-'0'));
else {
op2 = pop(&opndstk);
op1 = pop(&opndstk);
value = oper(c, op1, op2);
push (&opndstk, value);
}
return (pop(&opndstk));
}
float oper(symb, operand1, operand2)
int symb;
float operand1, operand2;
{
switch(symb){
case '+': return (operand1 + operand2);
case '-': return (operand1 - operand2);
case '*': return (operand1 * operand2);
case '/': return (operand1 / operand2);
default: printf("%s", "illegal operation");
exit(1);
}
}
push(ps, x)
struct stack *ps;
float x;
{
if(ps->top == MAXCOLS-1)
{
printf("%s", "stack overflow");
exit(1);
}
else
ps->items[++(ps->top)] =x;
return;
}
float pop(ps)
struct stack *ps;
{
int top;
if (top==-1)
{
printf("%s", "stack underflow");
exit(1);
}
else
return(ps->items[ps->top--]);
}