Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to evaluate a string expression and return the value in C?
    primarykey
    data
    text
    <p>I am trying to evaluate an expression taken as a character array and return the result of the expression.</p> <p>eg:</p> <pre><code>char *myeExpression []= "(1+2) * 3" </code></pre> <p>should return result 9.</p> <p>Here is my code:</p> <pre><code>struct node { double element; struct node *next; } *head; void push(int c); // function to push a node onto the stack int pop(); // function to pop the top node of stack void traceStack(); // function to //print the stack values int prece(char j) { if(j=='*'||j=='/') { j=3; } else { if(j=='+'||j=='-') { j=2; } else { j=1; } } return j; } int evaluate(char * a) { int i = 0, j = 0,k,l,a1,b1; // indexes to keep track of current position char *exp = (char *)malloc(sizeof(char)*100); double res = 0; char stack[5]; char tmp; head = NULL; // converting an infix to a postfix for(i=0;i&lt;10;i++) { a1=prece(a[i]); b1=prece(stack[k]); if(a1&lt;=b1) { exp[l]=a[i]; l++; } else { stack[k]=a[i]; k++; } } for(i=k;i&gt;0;i--) { exp[l]=stack[i]; l++; } //end i=0; j=0; k=0; while( (tmp=exp[i++]) != '\0') { // repeat till the last null terminator // if the char is operand, pust it into the stack if(tmp &gt;= '0' &amp;&amp; tmp &lt;= '9') { int no = tmp - '0'; push(no); continue; } if(tmp == '+') { int no1 = pop(); int no2 = pop(); push(no1 + no2); } else if (tmp == '-') { int no1 = pop(); int no2 = pop(); push(no1 - no2); } else if (tmp == '*') { int no1 = pop(); int no2 = pop(); push(no1 * no2); } else if (tmp == '/') { int no1 = pop(); int no2 = pop(); push(no1 / no2); } } return pop(); } void push(int c) { if(head == NULL) { head = malloc(sizeof(struct node)); head-&gt;element = c; head-&gt;next = NULL; } else { struct node *tNode; tNode = malloc(sizeof(struct node)); tNode-&gt;element = c; tNode-&gt;next = head; head = tNode; } } int pop() { struct node *tNode; tNode = head; head = head-&gt;next; return tNode-&gt;element; } </code></pre> <p>Infix Expression evaluation happens but not completely. Getting wrong result ie 3 in stead of 9.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload